Hi, if String s1="abc"; String s2=new String (s1); The == op if applied on this gives me false. But if I use it with trim() or replace() or toUpperCase() the == op returns true. Again if used with concat() it returns false. Correct me if I'm wrong but does the concat() return a new String() object ,and all the other methods return the same literal??very much confused. For eg. if(s1==s2)//false if("abc".trim()=="abc")//true if("abc".toUpperCase()=="ABC")//true if("abc".replace('c','t')=="abt")//true But if("abc".concat("fool")=="abcfool")//gives false?? Please tell me something about this. Also,can anybody tell me how to recover a lost source code file from the class file?I tried the javap option but I could not get it. Thanks, Vedhas Pitkar.
hi, 1) when u create a string with String s1="abc"; then JVM adds it to a String literal pool; so the next time if u create a string the same way the variable will point to the same mocation in the pool. For eg: String s1="abc"; String s2="abc"; now s1 & s2 point to the same "abc"; so s1==s2 will give u TRUE since == checks the memory address referenced by s1 & s2. whereas equals() method checks the contents of the memory address referenced by s1 & s2. 2) i checked "abc".replace('c','t')== "abc" it gives u false 3) "abc".toUpperCase()=="ABC" will also give u false. since both 2) & 3) create new String literals 4) "abc".trim()=="abc" will give u true since there is no change in the String literal and it returns the original string literal 5) String s1="abc"; String s2=new String(s1); s2 is not added to the string literal pool, instead a new literal is created. so, s1==s2 will give false s1.equals(s2) will give true
i suggest u read the JDK for the String functions. they have explained it very well out here. as for mock exam questions, i suggest u actually check the code for the right answer(in case u got the question wrong), because i have found that sometimes the exam does not give the right answer.
The lesson to learn here is to always use equals() to compare two Strings. For purposes of the certification exam, knowing the basic difference between == and equals() is good enough. I don't think you really need to remember all the quirks of the String methods so don't worry too much about it.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck
Wonderful explanation Namarata!!! It boils down to 2 basic things about string comparisions 1. Shallow comparison(==) 2. Deep comparison (equals) Since strings are immutable, JVM will not waste resources by creating multiple strings of same name.. and also to enhance reusablilty the strings are kept in the pool and reused often. However new String(), becomes altogether a different memeory space and the shallow will fail since they not sharing the same space on the pool. But to make that alienated string object into the pool, use intern(). Hope it helps Good luck Ragu