Could somebody explain why the result from case 1 is different from case 2. case1 : if("String".toString() == "String") case2 : if(" String ".trim() == "String") Thanks in Advance
Hi, case 1: Here "String" is returned as it is. API for toString() says "This object (which is already a string!) is itself returned." case 2:Here the white space from both the ends of the String is removed and a new String object is returned. Rashmi
The results should be true then false. The first returns true because using the toString method on a String simply returns the String itself. The compiler knows this and can just use the same string literal from the string pool for both of the Strings in the method. The trim method returns a new String that has had any leading and trailing whitespace removed. If there were no spaces it would return the same string (take out the spaces and run it and your output will be true, true). In the example you posted becasue there are spaces it returns a new String object. Because == compares the objects to see if they are the same the result is false. If you use the same String (with spaces but change == to equals then you'll get true, true. Because equals is overridden for Strings to compare the actual contents.