File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why code gives true ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why code gives true ?" Watch "why code gives true ?" New topic

why code gives true ?

Vishy Karl
Ranch Hand

Joined: Sep 08, 2003
Posts: 116
HI All,
Just experimenting why does the following code output true ??

Output is true. why ?

"The man who can drive himself further once the effort gets painful is the man who will win." <br />Roger Bannister
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
Hi Vishy, would you mind my modifying your code so it does return true?

You are creating two references that point to the same object, which is a String literal "works". Line Object o = "works"; declares an Object reference variable o, creates and interns a String "works", and assigns it to o; the line following it declares a String reference s and assigns it to "works" in the String constant pool.
== operator returns true if two references point to the same object on the heap. o==s is valid because String IS-A Object, so instanceof test passes OK. Otherwise, a compile error would've been thrown. Hope this helps.
[ December 07, 2003: Message edited by: Vad Fogel ]
Mohit Goyal
Ranch Hand

Joined: Nov 09, 2003
Posts: 65
well although the Reference types are different, the actual object is the same String in the String pool.
Since == checks only for the 2 references pointing to the same object it returns true in the above case.
Vishy Karl
Ranch Hand

Joined: Sep 08, 2003
Posts: 116
Thanks for your replies
I agree. Here's the link:
subject: why code gives true ?
It's not a secret anymore!