I am having an issue with getting a Scanner to read what is actually used as an input.  I have looked at every response that I could find to other people on this site, and have not yet found anything that works for the problem. I have written a test code that returns the result of a previous if/else statement so that I can try to find where the problem may be. I think that the scanner is only temporarily storing my input as a string, and then it becomes some other datatype.  public static String goAgain(String r)  {     if (r == "y")      {         return "y";     }     else {         System.out.println("Goodbye.");         return "n";     } } public static void main(String args[]) {     Scanner repeat = new Scanner(System.in);     System.out.print("Are you ready? ");     String again = repeat.next();     String user_response = goAgain(again);     System.out.println(user_response);     // (also tried System.out.prinln(again); }   What should happen is when the user inputs the letter y, the letter y should be returned to the goAgain method. What actually happens is something else ends up being inserted, and it returns something other than the letter y, and so prints "Goodbye" and the letter "n" to the console. Also, when the variable again is printed instead of user_response, it prints the letter y.
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?
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.
111151
Can I simply use  if(myString == nil)   For some reason a string that I know is null, is failing this statement.
24750
I've just encountered a weird problem, I'm trying to printf an integer variable, but I forgot to specify the variable name, i.e.  printf("%d");   instead of  printf("%d", integerName);   Surprisingly the program compiles, there is output and it is not random. In fact, it happens to be the very integer I wanted to print in the first place, which happens to be m-1.  The errorneous printf statement will consistently output m-1 for as long as the program keeps running... In other words, it's behaving exactly as if the statement reads  printf("%d", m-1);   Anybody knows the reason behind this behaviour? I'm using g++ without any command line options.  #include &lt;iostream&gt; #define maxN 100 #define ON 1 #define OFF 0  using namespace std;  void clearArray(int* array, int n); int fillArray(int* array, int m, int n);  int main() {     int n = -1, i, m;     int array[maxN];     int found;      scanf("%d", &amp;n);      while(n!=0)     {         found=0;         m = 1;         while(found!=1)         {             if(m != 2 &amp;&amp; m != 3 &amp;&amp; m != 4 &amp;&amp; m != 6 &amp;&amp; m != 12)             {                 clearArray(array, n);                 if(fillArray(array, m, n) == 0)                 {                     found = 1;                 }             }             m++;         }          printf("%d\n");          scanf("%d", &amp;n);     }      return 0; }  void clearArray(int* array, int n) {     for(int i = 1; i &lt;= n; i++)         array[i] = ON; }  int fillArray(int* array, int m, int n) {     int i = 1, j, offCounter = 0, incrementCounter;      while(offCounter != n)     {         if(*(array+i)==ON)          {             *(array+i) = OFF;             offCounter++;                }         else          {             j = 0;             while((*array+i+j)==OFF)             {                 j++;             }             *(array+i+j) = OFF;             offCounter++;                    }         if(*(array+13) == OFF &amp;&amp; offCounter != n) return 1;         if(offCounter ==n) break;          incrementCounter = 0;                while(incrementCounter != m)         {             i++;             if(i &gt; n) i = 1;             if(*(array+i) == ON) incrementCounter++;          }            }      return 0; }
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
70818
My question is on return values produced by this code:  if [ -n ]; then echo "true"; else echo "false"; fi   This prints true.  Its complementary test using [ -z ] also prints true:  if [ -z ]; then echo "true"; else  echo "false"; fi   In the above code, why does the [ -n ] test assume the string value that is not passed at all, as not null?  The code below prints false. This is expected since the passed string value is null and of zero length.  if [ -n "" ]; then echo "true"; else  echo "false"; fi
19898
Is there an efficient method of converting an integer into the written numbers, for example:  string Written = IntegerToWritten(21);   would return "Twenty One".  Is there any way of doing this that doesn't involve a massive look-up table?
5845
I tried to use java.io.FileReader to read some text files and convert them into a string, but I found the result is wrongly encoded and not readable at all.  Here's my environment:   Windows 2003, OS encoding: CP1252 Java 5.0   My files are UTF-8 encoded or CP1252 encoded, and some of them (UTF-8 encoded files)  may contain Chinese (non-Latin) characters.  I use the following code to do my work:     private static String readFileAsString(String filePath)     throws java.io.IOException{         StringBuffer fileData = new StringBuffer(1000);         FileReader reader = new FileReader(filePath);         //System.out.println(reader.getEncoding());         BufferedReader reader = new BufferedReader(reader);         char[] buf = new char[1024];         int numRead=0;         while((numRead=reader.read(buf)) != -1){             String readData = String.valueOf(buf, 0, numRead);             fileData.append(readData);             buf = new char[1024];         }         reader.close();         return fileData.toString();     }   The above code doesn't work. I found the FileReader's encoding is CP1252 even if the text is UTF-8 encoded. But the JavaDoc of java.io.FileReader says that:     The constructors of this class assume   that the default character encoding   and the default byte-buffer size are   appropriate.   Does this mean that I am not required to set character encoding by myself if I am using FileReader? But I did get wrongly encoded data currently, what's the correct way to deal with my situtaion? Thanks.
51462
If I grep a document that contains the following:  ThisExampleString  ...for the expression This*String or *String, nothing is returned. However, This* returns the above line as expected.  Whether the expression is enclosed in quotes makes no difference.  I thought the asterisk indicated any number of unknown characters? Why does it only work if it's at the start of the expression? If this is intended behavior, what do I use instead of the expressions This*String and *String?
92333
if ('text'.equals(str))   or   if ('text' == str)   Is there any difference? If yes, then what is it?   Added, after answered.  String q = 'teXt'; system.debug('teXt'.equals(q)); // true system.debug('teXt' == q);      // true system.debug('text'.equals(q)); // false system.debug('text' == q);      // true
27214
How can I return to the start of a line and overwrite what has already been output on the console? The following does not appear to work:  System.out.print(mystuff+'\r');
33769
I haven't had the chance to take any serious low-level programming courses in school. (I know I really should get going on learning the "behind-the-scenes" to be a better programmer.) I appreciate the conveniences of Java, including the ability to stick anything into a System.out.print statement. However, is there any reason why you would want to use System.out.printf instead?   Also, should I avoid print calls like this in "real applications"?  It's probably better to  to print messages to the client's display using some kind of UI function, right?
119715
Let's say I have a java program that makes an HTTP request on a server using HTTP 1.1 and doesn't close the connection. I make one request, and read all data returned from the input stream I have bound to the socket.  However, upon making a second request, I get no response from the server (or there's a problem with the stream - it doesn't provide any more input). If I make the requests in order (Request, request, read) it works fine, but (request, read, request, read) doesn't.  Could someone shed some insight onto why this might be happening? (Code snippets follow). No matter what I do, the second read loop's isr_reader.read() only ever returns -1.  try{         connection = new Socket("SomeServer", port);         con_out = connection.getOutputStream();         con_in  = connection.getInputStream();         PrintWriter out_writer = new PrintWriter(con_out, false);         out_writer.print("GET http://somesite HTTP/1.1\r\n");         out_writer.print("Host: thehost\r\n");         //out_writer.print("Content-Length: 0\r\n");         out_writer.print("\r\n");         out_writer.flush();          // If we were not interpreting this data as a character stream, we might need to adjust byte ordering here.         InputStreamReader isr_reader = new InputStreamReader(con_in);         char[] streamBuf = new char[8192];         int amountRead;         StringBuilder receivedData = new StringBuilder();         while((amountRead = isr_reader.read(streamBuf)) &gt; 0){             receivedData.append(streamBuf, 0, amountRead);         }  // Response is processed here.          if(connection != null &amp;&amp; !connection.isClosed()){             //System.out.println("Connection Still Open...");          out_writer.print("GET http://someSite2\r\n");         out_writer.print("Host: somehost\r\n");         out_writer.print("Connection: close\r\n");         out_writer.print("\r\n");         out_writer.flush();          streamBuf = new char[8192];         amountRead = 0;         receivedData.setLength(0);         while((amountRead = isr_reader.read(streamBuf)) &gt; 0 || amountRead &lt; 1){             if (amountRead &gt; 0)                 receivedData.append(streamBuf, 0, amountRead);         } }         // Process response here     }   Responses to questions: Yes, I'm receiving chunked responses from the server. I'm using raw sockets because of an outside restriction.  Apologies for the mess of code - I was rewriting it from memory and seem to have introduced a few bugs.  So the consensus is I have to either do (request, request, read) and let the server close the stream once I hit the end, or, if I do (request, read, request, read) stop before I hit the end of the stream so that the stream isn't closed.
87194
I've been told that code such as:  for (int i = 0; i &lt; x.length(); i++) {     // blah }   is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:  int l = x.length(); for (int i = 0; i &lt; l; i++) {     // blah }   Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?
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?
19442
I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).  Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.
102402
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.  I was kind of hoping that this would work  int? val = stringVal as int?;   But that won't work, so the way I'm doing it now is I've written this extension method  public static int? ParseNullableInt(this string value) {     if (value == null || value.Trim() == string.Empty)     {         return null;     }     else     {         try         {             return int.Parse(value);         }         catch         {             return null;         }     } }      Is there a better way of doing this?  EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?