Junior — Middle
How many lines of memory will be allocated on the heap when executing the expression: String a = "Hello " + "World";
sobes.tech AI
Answer from AI
When executing the expression:
String a = "Hello " + "World";
only one String object — the string "Hello World" — will be created in memory in the heap.
Explanation:
- Concatenation of string literals at compile time is combined into a single literal.
- Therefore, the expression is equivalent to
String a = "Hello World";. - The string "Hello World" will be placed in the string pool, which is located outside the heap memory, but the String object references this pool.
Thus, no additional String objects are created in the heap, only one object if it does not already exist in the string pool.