-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,424
  • 10
  • 46
  • 69
piggyback
  • 8,764
  • 13
  • 49
  • 79

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
  • 46,243
  • 25
  • 134
  • 239
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
  • 12,853
  • 1
  • 19
  • 36