Bird
0
0

Given the code below, what will be the output?

hard📝 Application Q15 of 15
Java - Strings and String Handling
Given the code below, what will be the output?
String s1 = "Java";
String s2 = new String("Java");
String s3 = s2.intern();
System.out.println(s1 == s2);
System.out.println(s1 == s3);

Why does this happen?
Afalse false - all are different objects
Btrue false - new String creates pooled string
Cfalse true - intern() returns the pooled string reference
Dtrue true - all strings are pooled automatically
Step-by-Step Solution
Solution:
  1. Step 1: Analyze s1 and s2 references

    s1 is a string literal in the pool, s2 is a new String object outside the pool, so s1 == s2 is false.
  2. Step 2: Understand intern() method effect

    s3 = s2.intern() returns the reference from the string pool for "Java", which is the same as s1, so s1 == s3 is true.
  3. Final Answer:

    false true - intern() returns the pooled string reference -> Option C
  4. Quick Check:

    intern() returns pool reference [OK]
Quick Trick: intern() returns pooled string reference [OK]
Common Mistakes:
  • Assuming new String() returns pooled string
  • Thinking '==' compares string content
  • Ignoring intern() method purpose

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes