string

How many objects are created by String code?

Puzzle:

String s1 = "abc"; String s2 = new String("abc"); String s3 = s2.toUpperCase();

Answer: 3 objects.

    • Created in the String Constant Pool (if not already there).
  1. new String("abc") - Created in the Heap.
  2. s2.toUpperCase() - Creates a new String "ABC" in the Heap because Strings are immutable.

Another Puzzle:

String s = "Hello"; s.concat("World"); System.out.println(s);

Output: "Hello" Objects: 3 created ("Hello", "World", "HelloWorld"), but s still points to "Hello".

How many objects are created by String code? | DevExCode