Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt 1 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt 1" Watch "Doubt 1" New topic

Doubt 1

Amitkumar Dhama
Ranch Hand

Joined: Feb 14, 2005
Posts: 56
Hi all can any body explain me,
Class A
public static void main(String [] args)
String s = new String("amit");
String s1 = s;
System.out.println(s.equals(s1)+" "+s==s1);
output of this code is false,although both equals() and "==" are returning true and that too only single false

this onme prints


thanking in advance

SCJP 1.4, SCWCD 1.4, M.Tech(CSE)
Glen Fernandes

Joined: Jan 28, 2005
Posts: 5

Quite simply, it's an operator precedence issue.
Operator == has the lowest precedence in that expression.

What you want instead is:

Otherwise the s.equals(s1)+" "+s is evaluated, yielding a new String with the value "true ". This is then compared to s1 with the == operator, which obviously yields false.


[ April 16, 2005: Message edited by: Glen Fernandes ]
[ April 17, 2005: Message edited by: Glen Fernandes ]
Amitkumar Dhama
Ranch Hand

Joined: Feb 14, 2005
Posts: 56
Thanks alot.....
even i was also thinking so but i wasn't sure of it......any ways Thanks 4 ur fast reply
I agree. Here's the link:
subject: Doubt 1
Similar Threads
String doubt
About == Operator
null String
equals() in Wrapper Classes
Java String pool problem