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?
Immutability of strings String objects are immutable: they can't be changed after they've been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.
Before we go ahead, One key point I would like to add that unlike other data types in Java, Strings are immutable. By immutable, we mean that Strings are constant, their values cannot be changed after they are created. Because String objects are immutable, they can be shared.
Strings are immutable. Once you have created a string you cannot later change that string object.
There are several ways that you can change a string variable into a numeric variable. One way is to use the number function with the compute command. To do this, you need to create a new variable using the compute command.
You can't change the value of errorText
in foo
as the method is currently declared. Even though you are passing a reference of the String errorText
into foo
, Java String
s are immutable--you can't change them.
However, you could use a StringBuffer
(or StringBuilder
). These classes can be edited in your foo
method.
public class Test { public static void foo(StringBuilder errorText){ errorText.delete(0, errorText.length()); errorText.append("bla bla"); } public static void main(String[] args) { StringBuilder error=new StringBuilder("initial"); foo(error); System.out.println(error); } }
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.
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