I have this very awkward question…
void changeString(String str){
str = "Hello world":
}
main(){
String myStr = new String("");
changeString(myStr);
}
When main returns, the value is still "" and not "Hello world". Why is that?
Also, how do I make it work? Let’s say I want my function changeString to change the string it got to “Hello world”.
Everyone explained why it doesn’t work, but nobody explained how to make it work. Your easiest option is to use:
Although the method name is a misnomer here. If you were to use your original idea, you’d need something like:
Your
ChangeableStringclass could be something like this:A quick lesson on references:
In Java method everything is passed by value. This includes references. This can be illustrated by these two different methods:
If you call
doNothing(obj)frommain()(or anywhere for that matter),objwon’t be changed in the callee becausedoNothingcreates a newThingand assigns that new reference toobjin the scope of the method.On the other hand, in
doSomethingyou are callingobj.changeMe(), and that dereferencesobj– which was passed by value – and changes it.