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
 
    