1

I have a question about String's immutability, namely, in the first situation the variable name does not change.

String name = "Unknown" ;  
name.concat("Boy"); 

System.out.println (name); 

But in the second case, the variable changes its value.

String name = "Unknown" ;  
System.out.println (name); 

name = "Test";
System.out.println(name);

Why the variable does not change in the first case, but in the second case as much as possible?

UnknownBoy
  • 169
  • 7
  • 1
    Because Strings are immutable.... every time you perform an operation on a string, it creates a new string.... `name = "Test";` this line here returns the reference of the new string and you store it in `name` – RobOhRob Sep 23 '19 at 18:26
  • 4
    `concat()` returns the new value/string, it does not change the current object in the variable `name`. – Progman Sep 23 '19 at 18:26

3 Answers3

3

Strings are immutable - they do not change.

The name variable is pointing to the string "Unknown"

If you look at the docs for String found here, you will see that concat() returns a String which is the brand new String that concatenates "Unknown" with "Boy".

The name variable is still pointing to the "Unknown" string.

In order for name to change you need to reassign it to the String returned by concat:

name = name.concat("Boy");

In the second example you're reassigning the reference to "Test".

None of the strings changed, just the references.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
Cwrwhaf
  • 324
  • 3
  • 5
2

Thats how string concatnation works. It doesnt concat to your existing string, but creates a new one.

String name = "Unknown" ;  
name.concat("Boy"); 

This creates and returns a new string "UnknownBoy" which you don't store. Refer to the String API for how the method behaves. https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#concat-java.lang.String-

Martin'sRun
  • 522
  • 3
  • 11
2

It looks you are confused between the reference variable and Object, in your case name is a reference variable of type String which can hold the reference to a String object. Please go through this for the understanding of reference, variable and object.

In your first case, name is a variable which holds the reference to the String Object "Unkown" and when name.concat("Boy") a new String object ("UnkownBoy") will be created but name variable still holds the reference to the old object ("Unkown") because you did not update the reference anywhere in the first case.

In your second case you have updated the reference variable by name = "Test"; , that means now name will hold the reference of a new String Object "Test".

Amit Bera
  • 7,075
  • 1
  • 19
  • 42