As written above, neither of this is necessary as instance variables
are assigned a default value (0 for integer types, null for
objects). If you want to assign them something different -- say
initialize counter to -1 -- either of the above works; personally I
prefer the former.
There is a slight difference to the two approaches if you're using
initializer blocks, as the following code demonstrates. Whether or not
this matters to you I don't know. This use of initializer blocks
doesn't seem advisable anyway.
public class Test
{
public static void main(String[] args)
{
new Before();
new After();
}
}
// Initializes the member before invoking the ctor
class Before
{
public int a = 1;
public void printA()
{
System.out.println("Before: " + a);
}
// Initializer block - gets run before ctor is invoked
{
printA();
}
}
// Initializes the member after the ctor is invoked
class After
{
public int a;
public After()
{
a = 1;
}
public void printA()
{
System.out.println("After: " + a);
}
// Initializer block - gets run before ctor is invoked
{
printA();
}
}
The output is:
bash-2.04$ java Test
Before: 1
After: 0