-3

I am interested in understanding whether there is any difference between initialising an object inside or outside the constructor

public class HTMLTable {
int value1;
Scanner user_input;

  public HTMLTable () {
    user_input = new Scanner(System.in);
    value = user_input.next();
  }
}

Instead of:

public class HTMLTable {
int value1;
Scanner user_input = new Scanner(System.in);

  public HTMLTable () {
    value = user_input.next();
  }
}

Can someone explain?

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
piggyback
  • 9,034
  • 13
  • 51
  • 80

2 Answers2

5

There's no difference: the compiler will move any outside initialization within the constructor.

See Java for a Nutshell, section 3.2.4: Field Defaults and Initializers.

sp00m
  • 47,968
  • 31
  • 142
  • 252
2

There is no difference. Compiler would move initialization code (like in 2nd example) into constructor body anyway. Chose this or that variant depending on readability of the code.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38