How is concatenation of final strings done in Java?

后端 未结 1 513
北荒
北荒 2020-12-06 09:50

When I compile this snippet.

public class InternTest {
    public static void main(String...strings ){
        final String str1=\"str\";
        final Strin         


        
相关标签:
1条回答
  • 2020-12-06 10:56

    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";
    
    0 讨论(0)
提交回复
热议问题