• Post Reply Bookmark Topic Watch Topic
  • New Topic

Behavior of == operator in case of Strings  RSS feed

 
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After the executing the code below:-

OUTPUT:- false true
false
Why did the output change in the second print statement?
Can anyone please explain?




 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vikran,
Welcome to CodeRanch! I gave you a cow for a great first question.

In the first print, Java is returning false because the Strings are different references and then true because they have the same String value.

In the second print, Java groups everything other than the == first making it look like this:


And since the string "new" is not the reference as the string "newtrue", it prints false.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again.
The + operator has a higher precedence than == but in the first line you are altering that with the ().
Go through the two expressions from left to right remembering the precedences. Also remember that in the first print you are not printing out a boolean. You are printing a String containing the words false and true.

And I think when Jeanne wrote before the == she might have meant after the ==.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I actually meant "other". Fixed.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can read more about the slightly strange behaviour of Strings in the old JavaRanch Journal article by Corey McGlone called Strings, literally.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!