tgoop.com/topJavaQuizExplain/295
Last Update:
What will be the output of the code?
❌ A. false true false true
❌ B. true true true true
❌ C. false false true true
❌ D. false false false true
✅ E. false true true true
❌ F. Error
❌ G. None of the above
Explanation:
1. String Pool and `intern()` Method:
- In Java, string literals (e.g., `"Hello, World!"`) are stored in the string pool.
- The intern()
method returns a canonical representation for the string object. If the pool already contains a string equal to the current string object, the string from the pool is returned.
2. Line 1: `System.out.println(str1 == str2);`:
- str1
is a string literal stored in the string pool.
- str2
is a new string object created using the new
keyword, so it is not in the string pool.
- The comparison ==
checks if both references point to the same object. Since str1
and str2
are different objects, the result is false
.
3. Line 2: `System.out.println(str1 == str3);`:
- str3
is assigned directly to str1
, so both references point to the same object in the string pool.
- Therefore, the result of str1 == str3
is true
.
4. Line 3: `System.out.println(str1 == str4);`:
- str4
is str2.intern()
, which returns the reference from the string pool.
- Since str1
is already in the string pool and str4
is now the interned version of str2
, both point to the same object.
- Thus, str1 == str4
is true
.
5. Line 4: `System.out.println(str1 == str5);`:
- str5
is the result of string concatenation using literals "Hello, "
and "World!"
. This concatenation is resolved at compile time, and the resulting string is stored in the string pool.
- Since str1
is "Hello, World!"
and str5
is also "Hello, World!"
stored in the pool, str1 == str5
is true
.
Output:
false
true
true
true
Correct Answer: E
BY Explanations “Top Java Quiz Questions”
Share with your friend now:
tgoop.com/topJavaQuizExplain/295