Reputation: 61
In the Java Language Specifications chapter on Definite Assignment, the Example 16-2 says that
A Java compiler must produce a compile-time error for the code:
{ int k; int n = 5; if (n > 2) k = 3; System.out.println(k); /* k is not "definitely assigned" before this statement */ }
even though the value of n is known at compile time, and in principle it can be known at compile time that the assignment to k will always be executed (more properly, evaluated). A Java compiler must operate according to the rules laid out in this section. The rules recognize only constant expressions; in this example, the expression n > 2 is not a constant expression as defined in §15.28.
But, if we look at §15.28, it says that
the relational operators <, <=, >, and >=
can contribute to a constant expression.
Is the expression n > 2
a constant expression or not? How can we determine this?
Upvotes: 2
Views: 139
Reputation: 234797
You've misread §15.28 of the spec. That section lists the language elements that are permissible in a constant expression. If the expression has anything not on the list, then it is not a constant expression. It does not mean (as you apparently read it to mean) that if any of the elements in the list is present then the expression is constant.
From the language spec (emphasis added):
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:
... etc.
The expression n > 2
is not a constant expression because n
is not declared final
and hence n
is not a constant. Even though its value at that point in the code can only be 5, that does not conform to the language definition of a constant. (See §4.12.4, which is referenced by §15.28.)
Upvotes: 1
Reputation: 279970
It says so because n
is not a constant expression.
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:
- [...]
- Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
and
A constant variable is a
final
variable of primitive type or typeString
that is initialized with a constant expression (§15.28).
n
is not final
and therefore isn't a constant variable. It therefore isn't a constant expression. And therefore n < 2
is not a constant expression.
Upvotes: 11