When you specify a type before the variable name, that is a declaration. Java allows you to initialize the variable being declared in the same line, which then makes it look like an assignment statement. Your confusion seems to be around the difference between a declaration/initialization and a plain old assignment statement.
The difference is simple: a declaration/initialization has a type specified on the left side whereas an assignment statement does not. Assignment statements must be inside a a code block, like a constructor, a method, or an initialization block.
Paul Clapham wrote:It's okay to put declarations in a class outside of any method. It's just not okay to put statements there.
With all respect Paul, I think it might read a bit confusing, not sure how that should sound more precisely though, but...
I think we all learned, that in Java, statements end with ";". So I guess seeing declaration ending with ";" makes to think that it is indeed statement and not something else - and of course that is true, regardless what kind of statement that is. However, I just looked up on google and found several occasions where the distinction is mentioned as "Declaration statements" and "Expression statements".
So maybe more precise answer would be:
Java, outside class allows to write "Declaration statements", while prohibits "Expression statements".
posted 2 months ago
When I looked up statements in the JLS this morning, I didn't see anything about declaration statements. I think people are going around creating new terms like. “declaration statement,” and. “expression statement,” and confusing people. Of course a ewb search can't tell you whether you are finding anything good; I bet I know where the next search for “declaration statement” will lead
Actually, I think “expression statement” is an official Java® term.
The fact that the JLS says things like,
If a declarator in a field declaration has a variable initializer, then the declarator has the semantics of an assignment (§15.26) to the declared variable.
I know what it means, but beginners wouldn't know.
I’m tired of walking, and will rest for a minute and grow some wheels. This is the promise of this tiny ad:
Create Edit Print & Convert PDF Using Free API with Java