Java Immutable String

    Immutable String

    Java strings are immutable means you cannot change or modify the string. Once you create the string object, its data and state remain unchanged, but you can create a new string object. Strings are immutable in Java because if many reference variables points to a single object and one of the reference variable change the object value it will affect the other reference variable.

    Example-

    class Simple{  
    
     public static void main(String args[]){  
    
       String s="Hello";  
    
       s.concat(" Welcome");
    
       System.out.println(s);
    
     }  
    
    } 

    Output-

    In the above example, we cannot change the Hello with the concat method. But if we assign the concat operation result to the string variable, then you can get the desired output.

    Example-

    class Simple{  
    
     public static void main(String args[]){  
    
       String s="Hello";  
    
       s=s.concat(" Welcome");
    
       System.out.println(s);
    
     }  
    
    } 

    Output-