• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

code behaving strangely

 
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wrote this code to test Strings equality

class str
{
public static void main(String arg[])
{
String s1="Hello";
String s2=new String("Hello");
String s3="Hello";
System.out.println(s1==s2+" , "+(s1==s3)); //Line 1
}
}

giving output: false instead of false , true

Replacing of Line 1 as System.out.println(s1==s2+" "+s1==s3); giving compiler error,"==" can't be applied to boolean and String.
 
Ranch Hand
Posts: 502
jQuery Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Change this



to this



will work.
 
Ramya Chowdary
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why System.out.println(s1==s2+" , "+(s1==s3)); giving output as "false" instead false , true
 
author
Posts: 23958
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by ramya sri:
why System.out.println(s1==s2+" , "+(s1==s3)); giving output as "false" instead false , true



The "+" operator has higher precedence than the "==" operator, so...

s1==s2+" , "+(s1==s3)

is basically like ...

s1==(s2+" , "+(s1==s3))

Henry
 
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, operator precedence is the clue.
 
eat bricks! HA! And here's another one! And a tiny ad!
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic