File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes code behaving strangely Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "code behaving strangely" Watch "code behaving strangely" New topic
Author

code behaving strangely

Pratap koritala
Ranch Hand

Joined: Sep 27, 2006
Posts: 252
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

Joined: Nov 16, 2005
Posts: 502

Change this



to this



will work.


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
Pratap koritala
Ranch Hand

Joined: Sep 27, 2006
Posts: 252
why System.out.println(s1==s2+" , "+(s1==s3)); giving output as "false" instead false , true
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18545
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Javier Sanchez Cerrillo
Ranch Hand

Joined: Aug 02, 2006
Posts: 152
Yes, operator precedence is the clue.


SCJP 5.0 95%<br /> <br />The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: code behaving strangely
 
Similar Threads
System.out.println(S1==S2)????????
Strings
question regarding String.intern()
Doubt in Strings
Two ways to construct a String/pool of strings problem