The following prints out "true",
String s = "231"; if(s == "231") { System.out.println("true"); } else { System.out.println("false"); }
This is because the lines are not changed, and java will try to save as much space as possible, therefore it points to the same memory link.
However, the following produces false:
String s = new String("231"); if(s == "231") { System.out.println("true"); } else { System.out.println("false"); }
new will force it to save the string in a new memory location.
By the way, you should ALWAYS use .equals() to compare strings (for cases like this)
Jesse Jun 15 '09 at 17:57 2009-06-15 17:57
source share