Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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
Sheriff
Posts: 38561
654
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: 60073
188
  • 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
Sheriff
Posts: 38561
654
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: 60073
188
  • 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!