Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

code behaving strangely

 
Ramya Chowdary
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • 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.
 
Prabhu Venkatachalam
Ranch Hand
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Change this



to this



will work.
 
Ramya Chowdary
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why System.out.println(s1==s2+" , "+(s1==s3)); giving output as "false" instead false , true
 
Henry Wong
author
Marshal
Pie
Posts: 21001
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Javier Sanchez Cerrillo
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, operator precedence is the clue.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic