How is concatenation of final strings done in Java?

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 says that

Simple names (§6.5.6.1) that refer to constant variables (§4.12.4) are constant expressions.

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 also says:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)
  • […]
  • The additive operators + and – (§15.18)
  • […]
  • Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).

Example 15.28-1. Constant Expressions

[…]

“The integer ” + Long.MAX_VALUE + ” is mighty big.”

Since those two variables are constant expressions, the compiler does the concatenation:

String str = str1 + str2;

is compiled the same way as

String str = "str" + "ing";

which is compiled the same way as

String str = "string";

Leave a Comment