Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt about references

 
Carlos G�mez
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the next code don't throws NullPointerException ?

Object o1 = new StringBuffer("sb");
Object o2 = new String("str");
Object o3 = o1;
o1 = null;
System.out.println(o3.toString());

SJCP 1.4, 1.5 In Progress
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Carlos G�mez:
why the next code don't throws NullPointerException ?

Object o1 = new StringBuffer("sb");
Object o2 = new String("str");
Object o3 = o1;
o1 = null;
System.out.println(o3.toString());

SJCP 1.4, 1.5 In Progress


In the third line, o3 and o1 become aliases of each other and refer to the StringBuffer object created in the first line.

When you set o1 to null, it doesn't change o3.
[ September 27, 2006: Message edited by: Keith Lynn ]
 
Chetan Raju
Ranch Hand
Posts: 109
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A single object with two references pointing to it. Once reference you set to null the other wont get affected.
 
Carlos G�mez
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why prints "false" when i check the references in line 5 and then prints "sb"?
which is the rule ?

Object o1 = new StringBuffer("sb");
Object o2 = new String("str");
Object o3 = o1;
o1 = null;
System.out.println(o3 == o1);
System.out.println(o3.toString());



Thank you
[ September 27, 2006: Message edited by: Carlos G�mez ]
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The == operator when used between references determines if they refer to the same object. Since you set o1 to null, it doesn't refer to the same object as o3 does.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic