Why can't I do assignment outside a method?

you need to do

class one{
 Integer b;
 {
    b=Integer.valueOf(2);
 }
}

as statements have to appear in a block of code.

In this case, the block is an initailiser block which is added to every constructor (or the default constructor in this case) It is run after any call to super() and before the main block of code in any constructor.

BTW: You can have a static initialiser block with static { } which is called when the class is initialised.

e.g.

class one{
 static final Integer b;

 static {
    b=Integer.valueOf(2);
 }
}

Because the assignments are statements and statements are allowed only inside blocks of code(methods, constructors, static initializers, etc.)

Outside of these only declarations are allowed.

This :

  class one{
        Integer b=Integer.valueOf(2);
  }

is a declaration with an initializer. That's why is accepted


In Java, when defining a class, you can define variables with default values and add methods. Any executable code (such as assignments) MUST be contained in a method.