File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt about references Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply 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: 2341
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: 2341
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: doubt about references
 
Similar Threads
Question about instanceof
Equals and == with Objects Problem
gc
grabage collection
islands of isolation(Garbage Collection)