-1

I have the following code, which I have written to check how string is immutable.

My code is:

class Check
{
   public static void main(String k[])
   {
      String a1="JohnPlayer";
      a1.concat("America");//line no 6
      String a2="America";//line no 7
      a1=a1+a2;//line no 8
      System.out.println("Value of a1="+a1);
   }
}

In line no 6, when I use concat, it print only "JohnPlayer", while If I concatenate a1 and a2 using a1+a2, it prints the concatenated value "JohnPlayerAmerica" . In this case, how can I say String is immutable?

Eran
  • 387,369
  • 54
  • 702
  • 768
user7344668
  • 37
  • 2
  • 7

1 Answers1

1

String is immutable.

a1.concat("America");

returns a new String instance which you ignore. a1 is unchanged.

a1=a1+a2;

creates a new String instance and assigns it to the a1 variable. The original String referenced by a1 is unchanged.

This is similar to writing :

a1 = a1.concat("America");
Eran
  • 387,369
  • 54
  • 702
  • 768
  • String doesn't provide any setter method..every time a new String only gets created – Chinmay Dec 27 '16 at 07:05
  • am not getting , these two line that is a1=a1+a2; i know that it assign these value but still it concat and print the value like JohnPlayerAmerica,while in first case it is not? – user7344668 Dec 27 '16 at 07:13
  • @user7344668 writing `a1.concat("America")` without doing anything with the returned new String has a similar meaning to writing `a1+a2` without doing anything with the returned new String. The only difference is that the latter doesn't pass compilation, since the result of the concatenation operator must be used somehow (assigned to a variable, returned to the calling method, etc...), while the result of a method call can be ignored. – Eran Dec 27 '16 at 07:18