-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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.