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 (§3.10.1, §3.10.2, §3.10.3, §3.10.4), string literals (§3.10.5), and text blocks (§3.10.6)
- Casts to primitive types and casts to type
String(§15.16) - The unary operators
+,-,~, and!(but not++or--) (§15.15.3, §15.15.4, §15.15.5, §15.15.6) - The multiplicative operators
*,/, and%(§15.17) - The additive operators
+and-(§15.18) - The shift operators
<<,>>, and>>>(§15.19) - The relational operators
<,<=,>, and>=(but notinstanceof) (§15.20) - The equality operators
==and!=(§15.21) - The bitwise and logical operators
&,^, and|(§15.22) - The conditional-and operator
&&and the conditional-or operator||(§15.23, §15.24) - The ternary conditional operator
? :(§15.25) - Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.
- Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
- Qualified names (§6.5.6.2) of the form TypeName
.Identifier that refer to constant variables (§4.12.4).
Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
Constant expressions are used as case labels in switch statements and switch expressions (§14.11, §15.28) and have a special significance in assignment contexts (§5.2) and the initialization of a class or interface (§12.4.2). They may also govern the ability of a while, do, or for statement to complete normally (§14.22), and the type of a conditional operator ? : with numeric operands.
Example 15.29-1. Constant Expressions
true
(short)(1*2*3*4*5*6)
Integer.MAX_VALUE / 2
2.0 * Math.PI
"The integer " + Long.MAX_VALUE + " is mighty big."