1

I'm trying to understand the String concatenation process. The below initialized variables (a, b, str) are all compile time constants.

When concatenating the compile time constants and comparing it with the equivalent string literals, it should return true, right?

But here it returns true for primitive value and false for a Wrapper class (Integer) variable.

I've gone through a few other SO posts, but I don't get this.

What's happening here?

final int a = 0;
final Integer b = 0;
final String str = ":ZERO";

String str1 = a + str;
String str2 = b + str;

System.out.println(str1 == "0:ZERO"); // true
System.out.println(str2 == "0:ZERO"); // false
Siva
  • 55
  • 1
  • 6
  • 1
    Does this answer your question? [What is the difference between == and equals() in Java?](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java). Read all posts. – DevilsHnd - 退職した Apr 07 '22 at 17:07
  • 3
    I wonder if [Compile-time constants and variables](//stackoverflow.com/q/9082971) is a suitable dupe. It says what are valid compile time constant types and wrapper aren't one. So it should answer the question. – Tom Apr 07 '22 at 17:09
  • @DevilsHnd I get the difference b/w == and .equals(), but in the above code, Integer b is a compile time constant, so the value of b could be inferred at compile time itself right.? – Siva Apr 07 '22 at 17:12
  • I just wanted to add a nice answer, why did you delete your question? – cyberbrain Apr 07 '22 at 17:14
  • 4
    @Siva No, `Integer b` is not a compile time constant. See my link. – Tom Apr 07 '22 at 17:14
  • @Jens This is not a dupe of == vs `.equals`, should be changed to the link Tom sent as this question is about compile-time constants. – Nexevis Apr 07 '22 at 17:16
  • 2
    the compiler does not know how the `Integer` class converts its content to string, neither that it is immutable; so `Integer`, or better, the result from calling its `toString` cannot be handled as a constant (at least not yet...) – user16320675 Apr 07 '22 at 17:24
  • 1
    also note that `final Integer b = 0;` is (much probably) being compiled as `final Integer b = Integer.valueOf(0);` which cannot be considered a compile time constant (the result of a method call) – user16320675 Apr 07 '22 at 17:38
  • @user16320675 That explains why `Integer b` is not a compile time constant, Thanks! – Siva Apr 08 '22 at 00:32
  • 1
    but also note that even if `b` was considered a compile time constant, doing `b + str` involves calling `b.toString()`, which also cannot be considered a compile time constant - the result cannot be *calculated* by the compiler. – user16320675 Apr 08 '22 at 06:48

0 Answers0