I found the following question Is Java "pass-by-reference" or "pass-by-value"?.
I read almost all of it, but could not find out yet what should I do if I want the foo(-) method, to change my String‘s value? (maybe or not reference too, it doesn’t matter to me).
void foo(String errorText){
errorText="bla bla";
}
int main(){
String error="initial";
foo(error);
System.out.println(error);
}
I want to see bla bla on the console. Is it possible?
You can’t change the value of
errorTextinfooas the method is currently declared. Even though you are passing a reference of the StringerrorTextintofoo, JavaStrings are immutable–you can’t change them.However, you could use a
StringBuffer(orStringBuilder). These classes can be edited in yourfoomethod.Other solutions are to use a wrapper class (create a class to hold your String reference, and change the reference in
foo), or just return the string.