• 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

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: 23951
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic