• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt - String Object  RSS feed

 
C Rakesh
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

Please help me to understand the following scenario.

private void stringTest(){
String confusion = null;
this.stringHelper(confusion);
System.out.println("stringTest.confusion -> "+confusion);
}

private void stringHelper(String confusion){
confusion = "Inside stringHelper";
System.out.println("stringHelper.confusion -> "+confusion);
}

Result
------
stringHelper.confusion -> Inside stringHelper
stringTest.confusion -> null

Question: How stringTest.confusion is coming null for String object? I know String object is immutable and in the method stringHelper(), I am changing the reference of "confusion" to another String object ("Inside stringHelper"). So as per my understanding, stringTest.confusion should alo changed to "Inside stringHelper", but it is not happening and still the value is null. Please guide me to understand where I am wrong.
 
Campbell Ritchie
Marshal
Posts: 55761
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please go back and add code tags to your post.

You are getting confused about pass‑by‑reference and pass‑by‑value. What you are describing is pass‑by‑reference, but that does not exist in Java. Have a look at this thread, where somebody else had a similar misunderstanding. If you have a week to read it, that is
 
C Rakesh
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Campbell!

This solved my doubt regarding String object. Since String object in Java is immutable and Java has Only pass-by-value, the original value will never change.

But it will work fine with other types of objects (Eg: List - Since List is mutable, I can pass the List object from first method to second method, and I can modify in the second method, the changes will be reflected in the first method too). Pleae correct me if I am wrong.

Thanks a lot again for the superfast response!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!