Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change String object's value passed to my method?

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?

like image 360
merveotesi Avatar asked Nov 21 '11 16:11

merveotesi


People also ask

Can you change the value of a string object?

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.

Can we reassign value to string in Java?

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.

Can the value of a string be changed after it is created?

Strings are immutable. Once you have created a string you cannot later change that string object.

Can we change string variable?

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.


1 Answers

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 Strings 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.

like image 199
Jack Edmonds Avatar answered Oct 05 '22 21:10

Jack Edmonds