Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 77
Question ID: UKOCP62170
Consider below code of Test.java file:
- package com.udayankhattry.ocp;
- public class Test {
- public static void main(String[] args) {
- String s1 = "1Z0-819";
- String s2 = "1Z0-819" + "";
- System.out.println(s1 == s2);
- }
- }
What will be the result of compiling and executing Test class?
- A 1Z0-819
- B true
- C false
- D Compilation error
Reveal correct answer
Correct answer: B
Explanation
UKOCP62170:
Please note that Strings computed by concatenation at compile time, will be referred by String Pool during execution. Compile time String concatenation happens when both of the operands are compile time constants, such as literal, final variable etc.
For the statement, String s2 = "1Z0-819" + "";, "1Z0-819" + "" is a constant expression as both the operands "1Z0-819" and "" are String literals, which means the expression "1Z0-819" + "" is computed at compile-time and results in String literal "1Z0-819".
So, during compilation, Java compiler translates the statement
String s2 = "1Z0-819" + "";
to
String s2 = "1Z0-819";
As "1Z0-819" is a String literal, hence at runtime it will be referred by String Pool.
When Test class is executed,
s1 refers to "1Z0-819" (String Pool object).
s2 also refers to same String pool object "1Z0-819".
s1 and s2 both refer to the same String object and that is why s1 == s2 returns true.
Please note that Strings computed by concatenation at run time (if the resultant expression is not constant expression) are newly created and therefore distinct.
For below code snippet:
String str1 = "1Z0-819";
String str2 = str1 + "";
System.out.println(str1 == str2);
Output is false, as str1 is a variable and str1 + "" is not a constant expression, therefore this expression is computed only at runtime and a new non-pool String object is created.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
