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?

Butiri Dan
  • 1,759
  • 5
  • 12
  • 18
RATAN KUMAR
  • 553
  • 6
  • 11
  • 1
    Because the first one is evaluated at compile time, so the strings got pooled. Duplicate. – user207421 Jul 28 '19 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). – Izruo Jul 28 '19 at 10:20
  • 4
    @Izruo It interns any *compile-time* string literal. – user207421 Jul 28 '19 at 10:20
  • Could you please eleborate the both statement. I didn't get. Thanks in advance – RATAN KUMAR Jul 28 '19 at 10:21
  • 1
    `"X="+10` can be evaluated at compile time. `"X="+x` cannot. – user207421 Jul 28 '19 at 10:22
  • 1
    @user207421 sorry to be pedantic, but an int literal concatenated with a string literal isn't a [string literal](https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-3.10.5): it's a ["constant expression of type `String`"](https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.28), which is guaranteed to be interned. – Andy Turner Jul 28 '19 at 14:18

0 Answers0