How does Java handle String objects in memory?

I was asked this question:

String s = "abc"; // creates one String object and one
          // reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,
                 // and one reference variable*

Based on the above details, how many String objects and how many reference variables were created before the println statement below the code?

String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);

My answer was The result of this piece of code is spring winter spring summer

There are two control variables: s1 and s2. There were eight String objects created as follows: "spring", "summer" (lost), "spring summer", "fall" (lost), "spring" lost, "spring summer spring" (lost), "winter" (lost), "spring winter" (currently "spring" is lost).

In this process, only two of the eight String objects are not lost.

Is it correct?

+5
4

: 2 8 .

String s1 = "spring "; //One reference and 1 object in string pool. (if it didn't exist already)

String s2 = s1 + "summer "; //Two references and 3 objects

s1.concat("fall "); //Two references and 5 objects

s2.concat(s1); //Two references and 6 objects

s1 += "winter "; //Two references and 8 objects

System.out.println(s1 + " " + s2);

: Java String ?

Java String.

  • str1 = "OneString";

JVM , , . , . , . , .

  1. String str1 = new String ( "OneString" );

JVM . - . , OneString .

:

intern() String. String , , . ( , , ).

:

Java ? " ( "s" )?

Java

+3

. SCJP btw.

concat , . s1 " spring

, Java:

Christian

+1

java . , . , - , .

+ , ( .

, -

+1
String s = "abc"; // creates one String object and one 
                 // reference variable 

, String.

String s = new String("abc"); // creates two objects,
                              // and one reference variable*  

. , intern() String.

String s1 = "spring "; 
String s2 = s1 + "summer ";        
s1.concat("fall ");        
s2.concat(s1);        
s1 += "winter ";
System.out.println(s1 + " " + s2);   

, , , System.out.println().:-)
(), , ( ).

+1

All Articles