| Author |
Check the output!!
|
Neha Dhaka
Greenhorn
Joined: Aug 30, 2005
Posts: 29
|
|
Please check the code below ,I am assigning null to s1 in a method ,but even after assigning null,when I print its value in main method and invoke a append method ,it does not give me null pointer exception. Please clarify ,thanks in advance . Raja
|
 |
Michael Ernest
High Plains Drifter
Sheriff
Joined: Oct 25, 2000
Posts: 7292
|
|
|
When you set s1 to null in x(), the "re-assignment" lasts only for the lifetime of the method. Once the method exits, the main() version of s1 is restored.
|
Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
|
 |
Neha Dhaka
Greenhorn
Joined: Aug 30, 2005
Posts: 29
|
|
But why the same is not applied when I am appending something to s1 ,and the appended value is displayed in the main method,also I am passing by referance so assigning the null should take effect in main method too. Please explain. Raja
|
 |
Tim Cao
Ranch Hand
Joined: Jul 26, 2004
Posts: 37
|
|
This is one of the few times you can see the problem clearer in C/C++ where the use of pointer is explicit. When you pass a parameter by reference (which applies for everything in Java that is an object), you can modify the value of parameter (which is actually the part of memory that your reference is referring to) but not the reference itself. That is why you can change the value of s1 by appending something to it but you cant make s1 refer to another memory location (be it null or another object). You can try assigning s1 = s2 in the example too. Hope this helps, T.
Originally posted by Raja Tonk: Please check the code below ,I am assigning null to s1 in a method ,but even after assigning null,when I print its value in main method and invoke a append method ,it does not give me null pointer exception. Please clarify ,thanks in advance . Raja
|
 |
 |
|
|
subject: Check the output!!
|
|
|