My friend sent me a question he saw in one mock exam for the Java certification about string objects:
String makeStrings(){ String s = "HI"; s = s + "5"; s = s.substring(0,1); s = s.toLowerCase(); return s.toString(); }
How many string objects will be created when this method is invoked? The correct answer the exam gave was 3. But I think it's five.
Am I wrong?
The answer is: 2 String objects are created.
In simple words, there can not be two string objects with same content in the string constant pool. But, there can be two string objects with the same content in the heap memory.
lang. String objects a and b are duplicates when a != b && a. equals(b) . In other words, there are two (or more) separate strings with the same contents in the JVM memory.
By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.
String makeStrings() { String s = "HI"; //String literal s = s + "5"; //concatenation creates new String object (1) s = s.substring(0,1); //creates new String object (2) s = s.toLowerCase(); //creates new String object (3) return s.toString(); //returns already defined String }
With respect to the concatenation, when creating a new String,JVM
uses StringBuilder
, ie:
s = new StringBuilder(s).append("5").toString();
toString()
for a StringBuilder
is:
public String toString() { return new String(value, 0, count); //so a new String is created }
substring
creates a new String object unless the entire String
is indexed:
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex) } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }
toString()
does NOT create a new String:
public String toString() { return this; }
toLowerCase()
is a pretty long method, but suffice it to say that if the String
is not already in all lowercase, it will return a new String
.
Given that the provided answer is 3
, as Jon Skeet suggested, we can assume that both of the String literals are already in the String pool. For more information about when Strings are added to the pool, see Questions about Java's String pool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With