Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java member initialization

Tags:

java

What is the difference between:

public class A
{
    private int x = 1;
    A() {}
}

and

public class A
{
    private int x;
    A() { x = 1; }
}

, if any?

like image 832
Luchian Grigore Avatar asked Sep 08 '11 06:09

Luchian Grigore


2 Answers

If you are asking from a practical point of view, the difference is that with the second form of initialization you will have to repeat it for every constructor that you write, were you to write many overloaded constructors.

like image 119
K-ballo Avatar answered Oct 07 '22 22:10

K-ballo


  1. In second case you repeating the of initializing x=0 because as it is instance variable so it will be initialized to 0 by default.
  2. This can be difference if multiple constructors will be there.else i dont think any other difference.
like image 33
Android Killer Avatar answered Oct 07 '22 23:10

Android Killer