Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • 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: 38257
623
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: 59131
180
  • 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: 38257
623
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: 59131
180
  • 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.
 
Hey! Wanna see my flashlight? It looks like this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!