| Author |
== and equals arent clear yet ... look at this
|
Ram Pathan
Greenhorn
Joined: May 18, 2002
Posts: 6
|
|
Thanks for your replies jessica,thomas and corey. I understood the Behaviour of string class as follows - CASE 1 ) String str1="a"; String str2="a" str1==str2 //true str1.equals(str2) //true CASE 2) String str1=new str1("a"); String str2=new str2("a"); str1==str2 //false str1.equals(str2); //true CASE 3) String str1=new str1("a") String str2="a" str1==str2 //false str1.equals(str2) //true CASE 4) GENERAL Object obj1=new Object(); Object obj2=new Object(); obj1==obj2 //false equals needs to be overridden by the class !! PLZ CORRECT ME IF I AM WRONG !! ================================================== Just when i thought i got the concept right ... I realised may be i didnt !!! Look at these questions from mock exams ....... Q 1) What is the output of the following StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2= new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1==sb2); //false System.out.println(sb1.equals(sb2)); //true System.out.println(sb1.equals(ss1)); //true System.out.println("Poddar".substring(3)); //dar Ans: a) false false false dar b) false true false Poddar c) Compiler Error d) true true false dar Correct Answer is a) MY QUESTION) WHY IS sb1.equals(sb2) FALSE ?? SO ALSO WHY IS sb1.equals(ss1) FALSE ?? Q 2) What is the output (Assuming written inside main) String s1 = new String("amit"); System.out.println(s1.replace('m','r')); //arit System.out.println(s1); //amit String s3="arit"; //arit String s4="arit"; //arit String s2 = s1.replace('m','r'); //arit System.out.println(s2==s3); //true System.out.println(s3==s4); //true a) arit amit false true b) arit arit false true c) amit amit false true d) arit amit true true Correct answer is a) s3==s4 is true because java points both s3 and s4 to same memory location in string pool MY QUESTION -> WHY IS S2==S3 FALSE ?? --------------------------------------------------
|
 |
Jamal Hasanov
Ranch Hand
Joined: Jan 08, 2002
Posts: 411
|
|
Hi, Rama. Don't try to remember all of this. Just try to understand it deeply. If you have RHE Book, then you can read about it in CHAPTER 8�The java.lang and java.util Packages String class Jamal Hasanov www.j-think.com
|
 |
Swati Gupta
Ranch Hand
Joined: May 28, 2002
Posts: 106
|
|
The answer to these are :-- MY QUESTION) WHY IS sb1.equals(sb2) FALSE ?? SO ALSO WHY IS sb1.equals(ss1) FALSE ?? MY QUESTION -> WHY IS S2==S3 FALSE ?? -------------------------------------------------- 1. The StringBuffer class does not override the equals method like String class so the sb1.equals(sb2) results false. The equals method on sb1(ref to StringBuffer class ) and ss1 (ref to String) will be false. 2. replace method od String class creates a String so S2==S3 will be false. Hope that helps. --Swati..
|
 |
 |
|
|
subject: == and equals arent clear yet ... look at this
|
|
|