0
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

  • 4
    Please refer to any of the 750 "how many strings are created by this code" questions here on SO. Several of them have **very** thorough descriptions of what goes on, the last thing we need is yet another one. – T.J. Crowder May 16 '15 at 07:03
  • @RealSkeptic, I stand corrected. – Aaron D May 16 '15 at 07:21

2 Answers2

0
  1. s = "Fred"
  2. s = s+47; => s = Fred47
  3. s = s.substring(2,5); => s = ed4
  4. s = s.toUpperCase(); => s = ED4
bud-e
  • 1,511
  • 1
  • 20
  • 31
  • @Aniket: I figured out the same way and it adds up to 4 objects, but the answer is only 3 objects are created and you have posted the same thing –  May 18 '15 at 17:20
-1

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.

codegasmer
  • 1,462
  • 1
  • 15
  • 47
  • can anybody explain me the reason for downvotes? did I say anything wrong – codegasmer May 16 '15 at 07:40
  • sorry I had to remove it as a answer because of downvotes and it made me think that may be your answer is wrong. Yes, even I would like people to comment instead of just down voting when I have already accepted it as an answer –  May 18 '15 at 17:23