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".
Strings in java are immutable, this means that once they are assigned a value, they cannot be changed, the code that seems to be changing the string actually makes a new object.
Java is officially always pass-by-value. The question is, then, “what is passed by value?” As we have said in class, the actual “value” of any variable on the stack is the actual value for primitive types (int, float, double, etc) or the reference for reference types.
String is immutable in java. you cannot modify/change, an existing string literal/object. String s="Hello"; s=s+"hi"; Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".
Everyone explained why it doesn't work, but nobody explained how to make it work. Your easiest option is to use:
String changeString() { return "Hello world"; } main() { String myStr = new String(""); myStr = changeString(); }
Although the method name is a misnomer here. If you were to use your original idea, you'd need something like:
void changeString(ChangeableString str) { str.changeTo("Hello world"); } main() { ChangeableString myStr = new ChangeableString(""); changeString(myStr); }
Your ChangeableString
class could be something like this:
class ChangeableString { String str; public ChangeableString(String str) { this.str = str; } public void changeTo(String newStr) { str = newStr; } public String toString() { return str; } }
In Java method everything is passed by value. This includes references. This can be illustrated by these two different methods:
void doNothing(Thing obj) { obj = new Something(); } void doSomething(Thing obj) { obj.changeMe(); }
If you call doNothing(obj)
from main()
(or anywhere for that matter), obj
won't be changed in the callee because doNothing
creates a new Thing
and assigns that new reference to obj
in the scope of the method.
On the other hand, in doSomething
you are calling obj.changeMe()
, and that dereferences obj
- which was passed by value - and changes it.
Java uses a call by value startegy for evaluating calls.
That is, the value is copied to str
, so if you assign to str
that doesn't change the original value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With