LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 2

Literals, new String and the pool Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        String a = "code";
        String b = "co" + "de";
        String c = new String("code");
        String d = c.intern();
        String part = "co";
        String e = part + "de";
        System.out.println((a == b) + " " + (a == c) + " " + (a == d) + " " + (a == e) + " " + a.equals(e));
    }
}
  • A true false true false true Correct
  • B true true true true true
  • C false false true false true
  • D true false false false true
Correct Answer: Option A

"co" + "de" is a compile-time constant, so it is the pooled literal. Concatenation with a variable happens at run time and creates a new object.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links