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);
 }
}

Leave a Comment