Confusion about line immutability

I have the following code: -

public class StaticImplementer {
    private static String str= "ABC";
    public static void main(String args[]) {
        str = str + "XYZ";
    }
}

Questions: -

  • Here String str is static, then where will this object be stored in memory?

  • Since String is immutable, where will the object for "XYZ" be stored?

  • Where will the destination be stored?

  • And how will garbage collection be collected?

+2
source share
2 answers

Here String str is static, then when will this object be stored in memory?

String is strnot an object; it is a reference to an object. "ABC", "XYZ"and "ABCXYZ"are three different String objects. Thus, strpoints to a string. You can change what it points to, but not what it points to.

Since String is immutable, where will the object for "XYZ" be stored?

, Mik378, "XYZ" - String, String, , "XYZ" .

?

"ABCXYZ" , , .

?

. Java 7, HotSpot JVM , permgen. Java JVM . , . -, permgen , permgen , JVM.

, , , String . , , , , .

+2

1) String str , , ?

, , variable static .
: Java, ?

2) String , "XYZ"?

: . .

3) ?

Java ( ), .
:

"This is a " +        // actually a string-valued constant expression,
    "two-line string"    // formed from two string literals

4) ?

, . , , "" .

+3

Source: https://habr.com/ru/post/1532266/


All Articles