What is meant by immutable?

后端 未结 17 1639
天命终不由人
天命终不由人 2020-11-22 02:27

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.

  1. Can somebody clarify what is meant by immutable? <
17条回答
  •  失恋的感觉
    2020-11-22 03:02

    Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed

    Consider bellow example,

    class Testimmutablestring{  
      public static void main(String args[]){  
        String s="Future";  
        s.concat(" World");//concat() method appends the string at the end  
        System.out.println(s);//will print Future because strings are immutable objects  
      }  
     }  
    

    Let's get idea considering bellow diagram,

    In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable. s, still refer to "Future". If you need to call "Future World",

    String s="Future";  
    s=s.concat(" World");  
    System.out.println(s);//print Future World
    

    Why are string objects immutable in java?

    Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

提交回复
热议问题