Issue
I want to send a string to a method and change the string there. The method should return void. Example:
String s = "Hello";
ChangeString(s);
String res = s;
//res = "HelloWorld"
-------------------------------------------
private void ChageString(String s){
s = s + "World";
}
How can I do it in Java? Can it be done without adding another class?
Thanks! PB
Solution
Your method cannot work with the current interface because of two reasons:
- Strings are immutable. Once you have created a string you cannot later change that string object.
- Java uses pass-by-value, not pass-by-reference. When you assign a new value to
s
in your method it only modifies the locals
, not the originals
in the calling code.
To make your method work you need to change the interface. The simplest change is to return a new string:
private String changeString(String s){
return s + "World";
}
Then call it like this:
String s = "Hello";
String res = changeString(s);
See it working online: ideone
Answered By - Mark Byers
Answer Checked By - Willingham (JavaFixing Volunteer)