1

Consider the java code below. The output which i got is written after the //

class test { public static void main(String[] args) { int x=10; System.out.println("X="+10 == "X="+10); // TRUE System.out.println("X="+x == "X="+x); // FALSE } } 

In both the lines String concatenation is going to happen but how the output is different?

6
  • 1
    Because the first one is evaluated at compile time, so the strings got pooled. Duplicate. Commented Jul 28, 2019 at 10:19
  • Actually, I'm quite fascinated by this. Obviously, java does not intern string literals only, but it interns any literal. It even 'works' for "X="+012 or "X="+0b1010 (just tested it). Commented Jul 28, 2019 at 10:20
  • 4
    @Izruo It interns any compile-time string literal. Commented Jul 28, 2019 at 10:20
  • 1
    "X="+10 can be evaluated at compile time. "X="+x cannot. Commented Jul 28, 2019 at 10:22
  • 1
    @user207421 sorry to be pedantic, but an int literal concatenated with a string literal isn't a string literal: it's a "constant expression of type String", which is guaranteed to be interned. Commented Jul 28, 2019 at 14:18

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.