objects in String constant pool in java

143 Views Asked by At
public class NewClass {

    public String makinStrings() {
        String s = "Fred";
        s = s + "47";
        s = s.substring(2, 5);
        s = s.toUpperCase();
        return s.toString();
    }
}

How many objects are created in the above program? I see as 4 objects after converting to uppercase string, but the answer is 3 according scjp book. I don't understand how come only 3 objects

2

There are 2 best solutions below

2
codegasmer On

Yes 3 objects

    String s = "Fred";             // created in pool
    s = s + "47";                  // created in heap
    s = s.substring(2, 5);         // created in heap
    s = s.toUpperCase();           // created in heap

If you see the source of substring() and toUpperCase() it returns a new string and s + "47"; since the value of s is determined at runtime it willl create new string so a total of 3 objects.

1
Aniket Samanta On
  1. s = "Fred"
  2. s = s+47; => s = Fred47
  3. s = s.substring(2,5); => s = ed4
  4. s = s.toUpperCase(); => s = ED4