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 ??
--------------------------------------------------