javaexpressionjls

Places where an expression can occur as per the JLS?


Consider the Article §15.1 regarding places where the expression can occur:

An expression occurs in either:

• The declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in an instance initializer, in a constructor declaration, in a method declaration, or in an annotation.

• An annotation on a package declaration or on a top level type declaration.

I don't think this is exhaustive list of all occurrence places for expression - as eg:

int a=23; //declaration of a local type
a=33; //this is re-initialization of the type

//or like a simple method invocation from inside a method like
foo();

Is the clause above correct - or is just a casual statement in the JLS?


Solution

  • That clause is actually true, though it is not stated in a precise way.

    For example:

    It is a matter of understanding what is meant by "in" in this context. It means "inside of" rather than "directly inside of".

    The imprecision arises when you consider that an expression statement that is inside of a method declaration that is inside of a class is ... also indirectly inside the class.

    You could argue that the clause descriptive rather than normative since they don't specify precisely what "in" means in this context. But even so, the description is correct if you interpret it as above.


    Your int a=23; "example" is not an expression, so it is not apropos to the point you are trying to make. It could be a statement, or it could be a (package private) field declaration that is "in" a class or interface declaration.