-4

Consider the two scenarios-

scenario 1:

class S{
   String s="hello";
   s="world";
   System.out.println(s);
}
public class StringImmutable{
    public static void main(String args[]){

    }

Result- it throws uncompiled code error at pkg.StringImmutable.main(StringImmutable.java:12)

but when i do this-

class S{
    String s="hello";

    void change(){
        s="world";
        System.out.println(s);
    }
}
public class StringImmutable{
     public static void main(String args[]){
         S s=new S();
         s.change();
     }
}

Result- world..it works just fine.

how is String immutable?enter code here

bosari
  • 1,922
  • 1
  • 19
  • 38
  • You need to differentiate variable from object. – Bhesh Gurung Jun 29 '14 at 08:55
  • 1
    If a string was immutable then `s1="hello"; s2=s1; s2.change();` would also change s1. What you're doing is changing s to **point to** a different string – Richard Tingle Jun 29 '14 at 08:55
  • When you do `s="world"`, `s` starts pointing to a new String object ("world"). `"hello"` remains as is in memory to be GCed later on. – Islay Jun 29 '14 at 08:55
  • @HussainAkhtarWahid'Ghouri':- i agree – rock321987 Jun 29 '14 at 08:56
  • New users can google like anyone else. "what does string is immutable mean" yields more than enough results. – Jeroen Vannevel Jun 29 '14 at 08:57
  • By the way your program is confused by the fact there are 2 variables called `s`, one is a string and the other is a mutable object containing a string – Richard Tingle Jun 29 '14 at 08:58
  • ok i understand that s is pointing to a new reference but why then the scenario 1 is not working? why it is throwing error ? why not it is pointing to another reference? – bosari Jun 29 '14 at 09:52
  • As it's written scenario 1 shouldn't even compile and has an empty main statement so wouldn't do anything anyway – Richard Tingle Jun 29 '14 at 09:55
  • @RichardTingle--first copy the scenario 1 and run it and then tell me..don't fire bullets in air – bosari Jun 29 '14 at 10:02

1 Answers1

4

You are creating new Strings - no mutation involved. Every time you think you edit a String (i.e. s1 = s1 + s2, s1 += s2, s1 = s1.substring( ...) its the creation of a new String, not a mutation.

Strings are not mutable by design.

Florian Salihovic
  • 3,921
  • 2
  • 19
  • 26