Why can't I do assignment outside a method?

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

but, if I initialize it during the creation, it works.

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

Inside a method, it works in both cases.

Answers


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.


This is the way java works, you cannot add non-declaration code (sorry i don't know the correct term) inside the class, that code should be inside methods.


A more general answer would be that the class body is about declarations, not statements. There is special provision for statements occuring in class body, but they have to be marked explicitly as either class initializers or instance initializers.


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.


Methods have the responsibility to perform mutations on the member variables. If the member variable needs to be initialized, java provides a way to do it during construction, class definition (latter case). But the mutation cannot be performed during definition.(former case). It is usually done at the method level.

Objects are meant to hold the state, while methods are meant to operate on that state.


Need Your Help

How do I automatically fix an invalid JSON string?

python json escaping

From the 2gis API I got the following JSON string.

Django self-referential foreign key

python django django-orm

I'm kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of...