Win a copy of Modern frontends with htmx this week in the Spring 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Behavior of == operator in case of Strings

 
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 41856
906
Eclipse IDE VI Editor Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 79078
376
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 41856
906
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I actually meant "other". Fixed.
 
Campbell Ritchie
Marshal
Posts: 79078
376
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic