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).
new String("abc")- Created in the Heap.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".