hi, this is from Abhilash's Quiz link (from mock exams available): a) if("String".trim() == "String".trim()) System.out.println("Equal"); else System.out.println("Not Equal");
b) if( "STRING".toUpperCase() == "STRING") System.out.println("Equal"); else System.out.println("Not Equal"); The answers to both these questions are: "the code will compile an print "Equal". " I tried this and ans is correct but I can't understand why? I know you java gurus will have an answer to "why"? Thanks, Deep
Hi, String methods, such as toUpperCase(), toLowerCase() and trim(), will return the original String object if NOTHING is changed on the string. Hope this helps. [ August 31, 2003: Message edited by: Alton Hernandez ]
Doesn't this question deal with how Java stores String objects on the heap? To keep the overhead down, if there is more than one copy of the same string in memory, both references to the string point to the same String object instead of making another object on the heap. This special region of memory is called the String constant pool. (Which is why Strings are immutable.) So the if statement, comparing the reference objects with the double equals, NOT the value of the String (a la String.equals()) will return true. The reference variables do have the same address in memory. Each new String literal is still a new reference to a string object. :-)
"There are only 10 types of people in the world, those who understand binary and those who don't."