Just started to learn Java. Please explain.

String firstString = new String("This is first string"); String secondString = firstString; 

As far as I know, in the second case in the secondString variable there should be a reference to the firstString object . But a copy of the object is created. The situation with other objects is quite different. Why? After all, is the String an object too?

    1 answer 1

    The second variable refers to the same string, nothing is copied. In Java and C #, strings are immutable , so it is not necessary to copy them when passing to another method, assigning variables, etc. Any change to the string will create a new instance, so if you change firstString , the value of secondString will not change, although they initially referred to the same instance of the string.

    Strings are not unique in this behavior. If you create an immutable class, all of whose methods will return a new instance, and the state of which instances cannot be changed externally, then this class will have the same behavior as a string.