Java instance variable declare and Initialize in two statements

You can’t use statements in the middle of your class. It have to be either in a block or in the same line as your declaration.


The usual ways to do what you want are those :

  • The initialization during the declaration

    public class MyClass{
        private int i = 0;
    }
    

    Usually it’s a good idea if you want to define the default value for your field.

  • The initialization in the constructor block

    public class MyClass{
        private int i;
        public MyClass(){
            this.i = 0;
        }
    }
    

    This block can be used if you want to have some logic (if/loops) during the initialization of your field. The problem with it is that either your constructors will call one each other, or they’ll all have basically the same content.
    In your case I think this is the best way to go.

  • The initialization in a method block

    public class MyClass{
        private int i;
        public void setI(int i){
            this.i = i;
        }
    }
    

    It’s not really an initialization but you can set your value whenever you want.

  • The initialization in an instance initializer block

    public class MyClass{
        private int i;
        {
             i = 0;
        }
    }
    

    This way is used when the constructor isn’t enough (see comments on the constructor block) but usually developers tend to avoid this form.


Resources :

  • JLS – Instance Initializers

On the same topic :

  • Use of Initializers vs Constructors in Java
  • How is an instance initializer different from a constructor?

Bonus :

What does this code ?

public class MyClass {
    public MyClass() {
        System.out.println("1 - Constructor with no parameters");
    }

    {
        System.out.println("2 - Initializer block");
    }

    public MyClass(int i) {
        this();
        System.out.println("3 - Constructor with parameters");
    }

    static {
        System.out.println("4 - Static initalizer block");
    }

    public static void main(String... args) {
        System.out.println("5 - Main method");
        new MyClass(0);
    }
}

The answer

Leave a Comment