0

In java String is a class and it is imutable so we can not change its value.In following code it will concate other string without any error.So I want to ask that if it is immutable then why in this following code value of String is changed??

import java.util.*;

public class conc
{
    public static void main(String args[])
    {
        String a="Sheetal";
        a=a+"Ga";
        System.out.println("Result:"+a);
    }
}
August
  • 12,410
  • 3
  • 35
  • 51
Sh87
  • 326
  • 2
  • 13
  • Because it's not a reference to the original `String` object? – August Aug 01 '14 at 07:26
  • `a = a + "Ga"` is actually creating an entirely "new" instance `String`. Try printing the `hashcode` of `a` before and after the assignment ;). Also try `String b = a + "Ga"` and print out both `a` and `b`... – MadProgrammer Aug 01 '14 at 07:26
  • You are correct , If you are not assigning with a new String :) – Suresh Atta Aug 01 '14 at 07:35
  • take some time reading about Strings and if you must ask a question, try researching existing questions in SO first, prior to asking such basic questions. – Pat Aug 01 '14 at 08:00

3 Answers3

6

In the code that you have shown, you have not changed the original String object.

Instead, you have created a new String object, which represents a + "Ga", and then re-assigned it to the reference variable a.

Note that all variables in Java other than primitive types are references.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
6

You are creating a new object by concatenating two strings, that is: You are not changing the object referenced by a but assigning to that reference the value referencing to a new String object.

0
 String a="Sheetal";
        a=a+"Ga"; // now this is not the same object you are referring early

When you alter your a will create a new String.

Your original String is not change that's why we call String are immutable and new String will create in the heap.

In this moment there are 2 object in your heap. now a is referring new Object.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115