| 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.
|
 |
 |
|
|
subject: doubt about references
|
|
|