wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt about references 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 "doubt about references" Watch "doubt about references" New topic
Author

doubt about references

Carlos G�mez
Ranch Hand

Joined: Sep 06, 2006
Posts: 56
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Aug 02, 2006
Posts: 109
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

Joined: Sep 06, 2006
Posts: 56
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

Joined: Feb 07, 2005
Posts: 2367
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.
 
Consider Paul's rocket mass heater.
 
subject: doubt about references
 
Similar Threads
gc
Question about instanceof
grabage collection
Equals and == with Objects Problem
islands of isolation(Garbage Collection)