Constant Expressions
A constant expression is an expression that always produces the same result. More precisely, a constant expression is an expression that produces a pure value of a primitive data type and is only composed of the following:
- Literals of primitive data types
- String literals
- Variables that are declared
finaland are initialized by constant expressions - Type casts to primitive data types or the type
String - The unary operators
+ -,~, and! - The binary operators *,
/,%,+,-,<<,>>,>>>,<,<=, >=,>, ==,!=,&,^,|,&&, and|| - The ternary operator
?:
Note that expressions that use ++, - -, and instanceof are not constant expressions. Also note that expressions that produce or contain references to objects that are not String objects are never constant expressions.
The compiler generally evaluates a constant expression and substitutes the result for the expression during the compilation process.
References Additive Operators; Bitwise/Logical Operators; Boolean Operators; Casts; Conditional Operator; Equality Comparison Operators; Interface Variables; Local Variables; Literals; Multiplicative Operators; Relational Comparison Operators; Shift Operators; Unary Operators; Variables