I am trying to ask the user for a simple 'yes' or 'no' response using:  Scanner user = new Scanner( System.in );  String response = user.nextLine();   I am then using the value of 'response' in a series of IF statements to output a specific piece of text.  However every time I enter in a response the program just terminates and I'm not sure what I am doing wrong.  Here's all of the code to make things more clear:  import java.util.Scanner;  public class vedant {  public static void main (String args[]){     System.out.println("Is it past 11.30pm?");     Scanner user = new Scanner( System.in );     String response = user.nextLine();     if (response == "yes") {         System.out.println("tut tut tut...");         user.close();     } else if (response == "no") {         System.out.println("Good boy");         user.close();     } }   }  BTW I'm new to Java so sorry if this is quite a basic mistake.
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
14488
I saw this in , in reference to shortcomings of the Java spec:  There are more shortcomings and this is a subtle topic. Check  out: public class methodOverloading{      public static void hello(Integer x){           System.out.println(&quot;Integer&quot;);      }       public static void hello(long x){           System.out.println(&quot;long&quot;);      }       public static void main(String[] args){          int i = 5;          hello(i);      } }  Here &quot;long&quot; would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all!  Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be &quot;long&quot; on the basis of i being declared as a primitive and not an object.  However, if you changed hello(long x)  to hello(Long x)  the output would print &quot;Integer&quot; What's really going on here?  I know nothing about the compilers/bytecode interpreters for java...
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
54977
Sometimes I need to ask the user for yes/no to confirm something.  Usually I use something like this:  # Yes/no dialog. The first argument is the message that the user will see. # If the user enters n/N, send exit 1. check_yes_no(){     while true; do         read -p "$1" yn         if [ "$yn" = "" ]; then             yn='Y'         fi         case "$yn" in             [Yy] )                 break;;             [Nn] )                 echo "Aborting..."                 exit 1;;             * )                 echo "Please answer y or n for yes or no.";;         esac     done; }   Is there a better way to do it? Is this utility maybe already in my /bin folder?
86373
Groovy adds the execute method to String to make executing shells fairly easy;  println "ls".execute().text   but if an error happens, then there is no resulting output.  Is there an easy way to get both the standard error and standard out?  (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)  It would be nice to have something like;   def x = shellDo("ls /tmp/NoFile")  println "out: ${x.out} err:${x.err}"
40125
Take the following sentence:     And even if the program inputted one token and then invoked newLine(), wouldn't it input a blank?   I've been told that this sentence has a clear pronoun reference. Why? Couldn't it refer to either program or token?
12184
I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
92456
Alright, I have been doing the following (variable names have been changed):   FileInputStream fis = null; try {     fis = new FileInputStream(file);      ... process ...  } catch (IOException e) {     ... handle error ... } finally {     if (fis != null)         fis.close(); }    Recently, I started using FindBugs, which suggests that I am not properly closing streams.  I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException.  What are people supposed to do here?  The Java libraries throw too many checked exceptions.
42746
Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit().  Does exit() do anything special that return doesn't?
40938
After I posted this question, I found a similar post that seemed to answer it: . I'll leave this in place for now, as I am not sure how to mark my own question as a duplicate  In attempting to debug a SOQL query error, I encountered a strange behavior with Database.query and bind variables. Specifically, when I run this code:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } Database.query(userQuery);   the Database.query statement executes with no errors, despite the fact that the variable firstNames does not exist in its context. However, when I add an else clause:  String userQuery = 'SELECT Id FROM User'; if (true) {     List&lt;String&gt; firstNames = new List&lt;String&gt;{'James','Joe'};     userQuery += ' WHERE FirstName IN :firstNames'; } else {     List&lt;String&gt; firstNames; } Database.query(userQuery);   I receive a null object reference exception. It seems like Salesforce is checking to see if the variable is only declared once beforehand and, if so, uses its value in the context it was declared. This seems strange to me, so I was wondering if anybody here has any insight into what is going on under the hood.
110820
I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:   "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false   As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?  Exception Message:  System.JSONException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [line:1, column:3699]  Updated with sample Code   public class ResponseWrapper{     // fields from JSON to auto map     public Integer messageSeq;     public String Description;     public String messageTS;     public Integer messageLevel;     public Boolean isSystemMessage;     // parsing fields     private ResponseWrapper theResponse;     private JSONParser parser;      public void parse(String jsonString){         parser = JSON.createParser(jsonString);         parseJSON();     }      private void parseJSON(){            while (parser.nextToken() != null) {             if (parser.getCurrentToken() == JSONToken.START_OBJECT) {                 theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                            }         }     } }  String responseString = '{"MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false}'; system.debug('\n\nBEFORE\n' + responseString); ****Place code in here to test such as ReplaceALL*** ResponseWrapper parser = new ResponseWrapper(); parser.parse(responseString);
41167
I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities. What is the difference, specifically in PHP?  Does it have something to do with ===?
16499
If yes, on which operating system, shell or whatever?  Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):  public class ExitCode {     public static void main(String args[]) {         System.exit(Integer.parseInt(args[0]));     } }   Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)  &gt; java ExitCode 2; echo $? 2  &gt; java ExitCode 128; echo $? 128  &gt; java ExitCode 255; echo $? 255  &gt; java ExitCode 256; echo $? 0  &gt; java ExitCode 65536; echo $? 0     EDITED: the (only, so far) answer below fully  explain what happens on UNIXes. I'm still wondering about other OSes.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
11109
I've been having a lot of problems trying to figure out how to use scanf().  It seems to work fine with integers, being fairly straight forward scanf("%d", &amp;i).  Where I am running into issues is using scanf() in loops trying to read input.  For example:  do {   printf("counter: %d: ", counter);   scanf("%c %c%d", &amp;command, &amp;prefix, &amp;input); } while (command != 'q');    When I enter in a validly structured input like c P101, it seems to loop again before prompting me.  This seems to happen even with a single:  scanf("%c", &amp;c)    in a while loop.  It'll do the loop twice before prompting me again.  What is making it loop twice, and how do I stop it? When I enter in less amount of input that programmatically wouldn't have another character or number such as q, pressing enter seems to prompt me to enter more.  How do I get scanf() to process both single and double character entries?
8464
How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.  I could do   System.out.print(char1); System.out.print(char2); System.out.print(char3);   But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.  Thanks