Daniyal Javaid Daniyal Javaid - 1 year ago 97
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;


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download