Karthikayini Devi wrote:What is going on here? First time it prints true for the comparison, and next time, it prints false?? And Whatever inside the quotes in third SOP is also not printed out!! Why???
Probably the #1 topic on the Beginners forum, and I blame the SCJP exams.
You might want to have a look at the most recent thread, but the fact is that you should almost NEVER use '==' when comparing Strings (or any other object type). Use equals().
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
As Winston said you should never use == to compare Strings(or for that matter any Object). you should always use equals(). the == operator is for referential equality. it return true only if the references refer to same object. the first SOP output is simple. the second returns true, which means the references s1, s2 point to same object. this is also expected because of string pool . there is only one string object with the value "abc" and the two refernces are merely referencing it. now the third one is based on operator precedence. if you look at the operator precedence chart, you will find that + operator has HIGHER PRECEDENCE than == . So it will be executed first resulting in string concatenation, which gets compared with "abc", which as you might have guessed at this point of time will return false.
Karthikayini Devi wrote:Gurpreet, if string concatenation happens first, where is the concatenated string? Why it prints only false? It should print "s1==s2false" right?
Could you kindly explain me little elaborately?
the expression is "s1==s2" + s1==s2
since + has higher precedence "s1==s2" + s1 will be evaluated. this will result in concatenation to produces trueabc . this will be compared to s2(which points to string with value abc). here since the objects are different , the == operator will return false. did you get it ? if you still have any doubt , feel free to ask