0

I understand that Immutable objects are objects that cannot be modified. But string can be modified when we use functions. So how do we say string are immutable? this was a question asked interview. Need answer asap

Nithya
  • 41
  • 1
  • 2
  • 5
  • 1
    Similar post here - http://stackoverflow.com/questions/1552301/immutability-of-strings-in-java – mtk Mar 04 '13 at 14:05

4 Answers4

5

But string can be modified when we use functions.

No, what you get back is a different string. Example:

String a, b, c;

a = "testing 1 2 3";
b = a.substring(0, 7);  // Creates new string for `b`, does NOT modify `a`
c = a.substring(8);

System.out.println(b);  // "testing"
System.out.println(c);  // "1 2 3", proves that `a` was not modified when we created `b`

As you can see, the string "testing 1 2 3" was not modified by the substring call; instead, we got back a new string with just "testing".

String objects are immutable in Java because they provide no methods that modify the state of an existing String object. They only provide methods that create new String objects based on the content of existing ones.

(The above is, of course, unless you play very naughty games indeed with reflection.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • i know what you explained is 100 % right , just need a little more explanation in expert words , a = a+ " something" , now , System.out.println(a); , most definitely its altered , please put your expertt explanation to this – Hussain Akhtar Wahid 'Ghouri' Nov 05 '13 at 06:33
  • 4
    @HussainAkhtarWahid: In `a = a + " something";`, the string `a` *used* to point to is unchanged, but a *new* string is created and `a` is updated to point at the new string. Anything that had a reference to the old string is unaffected. Try `String a, b; a = "one"; b = a; a = a + " two"; System.out.println(b);"` and you'll see that the previous string was unchanged, and `b` still points to it. – T.J. Crowder Nov 05 '13 at 07:50
1

One more thing is that when you create a string, a block of memory is assigned for it in the heap, and when you change its value, a new block of memory is created for that string, and the old one becomes eligible for garbage collection, for example

String first = "xyz";    
String second = "xyz";    
second = "abc";

Now when first is created a block of memory is kept for 'first' in the heap, and for 'second' new space is not allocated as they point to the same thing, therefore second points to the same space in heap, lastly when second's value is changed it points to a new memory location. Hence strings are immutable because it's contents are never changed.. they are deleted and new contents are assigned... Use the dubugger and see how the memory is occupied.. and notice the same thing with primitive datatypes... there contents change not their memory locations..

Hope it helps!

fthiella
  • 48,073
  • 15
  • 90
  • 106
Eric B.
  • 4,622
  • 2
  • 18
  • 33
0

Reason 1. String is an object in java. So you can not change at any time..As an example

String s= new String ("Md Omar Faroque");                                                                 
s.concat("anik");   
System.out.println(s);   

Output will be: "Md Omar Faroque".

Why is that? When you added "Anik" with "Md Omar Faroque", it becomes a new String called "Md Omar Faroque Anik". This new String is not referenced to any new variable. S is still a reference variable for "Md Omar Faroque".

Take another example:

1. String s1 = "spring ";  
2. String s2 = s1 + "summer ";  
3. s1.concat("fall ");  
4. s2.concat(s1);  
5. s1 += "winter ";  
6. System.out.println(s1 + " " + s2);  

Output should be "spring winter spring summer"

Why is that? In line 5, s1 becomes a new String "spring winter". It forgot about the previous value "spring". As s1 referenced to "spring winter" now, so it has printed.
In the line 2, s2 referenced to "spring summer". so it has printed though in the line 2, it has concatenated again with s1 and it created new string "spring summer spring". But no new variable referenced to this value "spring summer spring", still s2 pointed to "spring summer".

Arman H
  • 5,488
  • 10
  • 51
  • 76
Omar Faroque Anik
  • 2,531
  • 1
  • 29
  • 42
-1
public class Example{

    public static void main(String[] args) {
        String s = "hello";
        String a = s;
        if (a == s) {// it will print if part of statement
            System.out.println("same reference");
        } else {
            System.out.println("not same reference");
        }
        s = "hi";// now we have change this 's'
        if (a == s) { // if we have changed the same s reference the it should
                        // print same reference
            System.out.println("same reference");
        } else {
            System.out.println("not same reference");// but it will printed
        }

    }

}
josliber
  • 43,891
  • 12
  • 98
  • 133
  • 1
    here the main thing to notice is that every time you change or update the same sting the new memory block will created (a new reference created). – DJ developer Jun 14 '15 at 18:30