• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Check the output!!

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
High Plains Drifter
Posts: 7289
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
reply
    Bookmark Topic Watch Topic
  • New Topic