• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check the output!!

 
Neha Dhaka
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Neha Dhaka
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic