Originally posted by Roger Chan:
I have some doubts in the following code snippet:
public class Why {
public static void main(String argv[]) {
String message = "hello";
new Why().run(message);
System.out.println(message);
}
public void run(String text) {
text += " world,";
System.out.println(text);
}
}
The output is "hello world, hello". I am wondering why the answer is not "hello world, hello world". As the method parameter being passed is a String object type, after the execution of the run() method, the parameter should be changed accordingly as well.
Thanks.
Think Big . So shall you become big.
Originally posted by FEI NG:
Java pass by reference which means it makes a copy of (message) and pass that to the method (text). Since it is a copy it will go away when the method ends. So, the original reference (message) will be used again in your main method.
Thus,
message ----> "hello"
text (copy) ----> "hello" same hello.
text += " world,";
text ------> "hello world" new String Object.
when the method ended text goes away and "hello world" go away.
Hope this help.
Originally posted by Dong Fu:
What if
static String message="hello";
?
Originally posted by Chin Loong:
is this because of the immutability of string?
for other data types like Vector, it's passed by reference, right? (just to make sure ^_^)
Cheers, <img src="smile.gif" border="0"> <br /><a href="http://www7.brinkster.com/manoj9/" target="_blank" rel="nofollow">Manoj</a><br />(<a href="http://www7.brinkster.com/manoj9/" target="_blank" rel="nofollow">http://www7.brinkster.com/manoj9/</a>)
Originally posted by Chin Loong:
fei ng : so, other than [b]String, which other objects are passed by value like the question above, rather than passed by reference?[/B]
"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
regards, Amit
coffee drinker and Sun Certified Programmer for Java 2 Platform
I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
|