How is concatenation of final strings done in Java?

守給你的承諾、 提交于 2019-11-27 23:33:16

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";
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!