How does Java handle String objects in memory?
Asked Answered
A

4

6

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 above details how many String objects and how many reference variables were created prior to the println statement of below 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 code fragment is spring winter spring summer

There are two reference variables, s1 and s2. There were a total of eight String objects created as follows: "spring", "summer " (lost), "spring summer", "fall" (lost), "spring fall" (lost), "spring summer spring" (lost), "winter" (lost), "spring winter" (at this point "spring" is lost).

Only two of the eight String objects are not lost in this process.

Is it correct?

Agitation answered 25/1, 2012 at 6:26 Comment(1)
Something good to know: #7663752 Note that my answer to this question was wrong...Octangle
M
4

Answer is: 2 references and 8 objects.

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);

Now your question: How does Java handle String objects in memory?

Java provides two ways to create object of class String.

  1. String str1 = "OneString";

In this case, JVM searches the string pool to see if equivalent string exist already. if yes, returns the reference to same. if not, adds it to string pool and returns the reference. So a new object may be created OR may not be.

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

Now, JVM has to create an object on heap. due to new. it doesn't matter if OneString is already present in string pool.

You can also put a string to pool:

You can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there).

You may like to look at following links:

What is the Java string pool and how is "s" different from new String("s")?

Questions about Java's String pool

Mcbryde answered 25/1, 2012 at 7:25 Comment(0)
L
1

Looks correct. This is a SCJP exam question btw.

concat returns a new String, this is lost. The first s1 is overridden with "spring winter "

Two things you should know about Strings in Java:

Cheers Christian

Lederman answered 25/1, 2012 at 6:42 Comment(2)
Could you comment more on Not every time you write new String("Summer") a completely new String ist constructed? By using "new", new java.lang.String object must be constructed (ie. two strings are not same when comparing them by ==). However, those two distinct String instances can share underlying char[] array (under certain conditions).Derte
Yes, I typed to quickly. You are right, the String Object is constructed - I just meant the "String" itself might not need more memory, because it is in the string pool. Please also see: docs.oracle.com/javase/1.4.2/docs/api/java/lang/…Lederman
D
1

Strings in java are immutable. There is allocated character array, and some surrounding information like offset and length. In case you are using string literals to initialize your strings, compiler tries to optimize and will create only one string object for each literal - this is possible because they are immutable.

If you do concatenation or + on strings, then new string will be alloacted and data compied together (with performance penalty.

Contrary to this, creating substring out of string is virtually free - no data will be copied

Debauch answered 25/1, 2012 at 6:44 Comment(0)
L
1
String s = "abc"; // creates one String object and one 
                 // reference variable 

Creates one string object only if the object doesn't present on the String Constant Pool already.

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

This actually creates only one object in the heap. It adds this object to pool if and only if the intern() method is called on this String object.

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

You explanation seems ok, except you have one more string in System.out.println().:-)
When you say (lost) it actually means that it is no more live object (reference is not present on the stack).

Lusatian answered 25/1, 2012 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.