Why can't I do assignment outside a method?

前端 未结 7 1962
不知归路
不知归路 2020-11-22 00:12

If I try to assign a value to a variable in a class, but outside a method I get an error.

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

b

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 00:47

    I think terminology-wise, couple of other answers are slightly off. Declarations are also statements. In fact, they are called "declaration statements", which are one of the three kinds of statements. An assignment statement is one form of "expression statement" and can be used only in constructs such as methods, constructors, and initializers. Check out the Statements section in this Oracle's tutorial link.

提交回复
热议问题