Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why code gives true ?

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI All,
Just experimenting why does the following code output true ??

Output is true. why ?
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic