Daniyal Javaid Daniyal Javaid - 3 months ago 31
Java Question

Assignment operation in java classes

What is the reason java allows Initialization in classes, that is

int a;
int a =5;

but does not allow assignment operation like

int a;



The second part, a=5; is an assignment expression, and expressions are in Java only allowed in defined places, namely inside variable declarations and inside code blocks. Code blocks are the bodies of methods, constructors or initializers. Yours is none of the above.

Basically, inside a class definition you can have any of the following:

  • Method declaration
  • Constructor declaration
  • Field declaration (with optional initialization)
  • Nested type declaration (class, interface, enum)
  • Initializer block (static or instance)

Everything else, apart from comments, is illegal.

So in your case, you could make your code legal by adding curly braces:

int a; { a=5; }

Now the assignment happens inside an initializer block, which will be executed after the constructor. But I wouldn't recommend doing it, it's non-obvious and considered an antipattern.