-2

I am trying use String.replace(oldChar,newChar) , but this returns a Changed string. Example:

String tempString= "abc is very easy";
String replacedString=tempString.replace("very","not");
System.out.println("replacedString is "+replacedString);
System.out.println("tempString is "+tempString);

OUTPUT :

replacedString is abc is not easy
tempString is abc is very easy

So my question is there any way to replace string without storing it in another String.

I want output of

String tempString= "abc is very easy";
tempString.replace("very","not");
System.out.println("tempString is "+tempString);

as

tempString is abc is not easy.

by using replace function.

Dhanraj
  • 1,162
  • 4
  • 18
  • 45

2 Answers2

5

Strings are immutable. They cannot change. Any action you perform on them will result in a "new" string that is returned by the method you called upon it.

Read more about it: Immutability of Strings in Java

So in your example, if you wish to change your string you need to do to overwrite the variable that references your original string, to point to the new string value.

String tempString= "abc is very easy";
tempString = tempString.replace("very","not");
System.out.println("tempString is "+tempString);

Under the hood for your understanding:

Assign String "abc is very easy" to memory address 0x03333
Assign address 0x03333 to variable tempString
Call method replace, create new modified string at address 0x05555
Assign address 0x05555 to temp String variable
Return temp String variable from method replace
Assign address from temp String variable to variable tempString
Address from tempString is now 0x05555.
If string at 0x03333 was not in code defined string and in StringPool String at address 0x03333 will be garbage collected.

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
  • Here you are still storing the result in string..any way without storing it ,just get result dynamically – Dhanraj Mar 12 '19 at 10:03
  • @Dhanraj you can not change a string "dynamically". Once you change something, a new String object gets created. You need to re-assign this to itself or a new String object. – Zun Mar 12 '19 at 10:04
  • @Dhanraj I added an explanation of how it works ish under the hood. – Tschallacka Mar 12 '19 at 10:04
-1

You can reassign tempString with its new value :

String tempString= "abc is very easy";
tempString = tempString.replace("very","not");
System.out.println("tempString is "+tempString);

Result is :

tempString is abc is not easy

Best

Maxouille
  • 2,729
  • 2
  • 19
  • 42
  • 1
    We posted at the same time ^^' The other answer was not complete at the time I posted and has been updated and filled with details after. I did not want to post the same answer. – Maxouille Mar 12 '19 at 10:03