Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java why would one initialize an int variable with 0 when it will be assigned 0 only by default when declared?

Tags:

java

int

What purpose does it serve?

Just read an example in a book where the author has done so.

int numOfGuesses=0;
like image 539
Serenity Avatar asked May 16 '10 10:05

Serenity


3 Answers

The automatic assignment to zero only applies to members, not to local variables. If it is a local variable and the = 0 is omitted then that variable has no value, not even zero. Attempting to use the value before it is assigned will result in a compile error. For example this code attempts to use an uninitialized local variable:

public class Program
{   
    public static void main(String[] args)
    {
        int numOfGuesses;   // local variable
        System.out.println(numOfGuesses);
    }
}

and produces this compile error:

Program.java:6: variable numOfGuesses might not have been initialized
        System.out.println(numOfGuesses);

Whereas this code using a member works and outputs zero:

public class Program
{   
    int numOfGuesses; // member variable

    public void run()
    {
        System.out.println(numOfGuesses);
    }

    public static void main(String[] args)
    {
        new Program().run();
    }
}

For members I tend to assign to zero explicilty if my code uses the fact that the initial zalue is zero, and omit the assignment if my code doesn't use the initial value (for example if it the value is assigned in the constructor or elsewhere). The result is the same either way, so it's just a style issue.

like image 156
Mark Byers Avatar answered Oct 13 '22 22:10

Mark Byers


It's more explicit; some people like. Note that this applies only to fields -- local variables need to be initialized; there are no defaults.

like image 29
Artefacto Avatar answered Oct 13 '22 21:10

Artefacto


The Java compilation and runtime differ.

When running the program, all classes are loaded with class loaders and they do the following:

This is done when class is used for the first time. Their execute order is defined by their order in the code.

  • run static blocks

    static{
    //do something here
    }
    
  • initialize static variables

    public static int number;

This will be initialized to zero 0;


The next group of initializations done is when creating an object.Their execute order is defined by their order in the code.

  • run non-static block

    {
    // do something here 
    }
    
  • initialize non-static(instance) variables

    public int instance_number;


And this is when and why there is default initialization! This is not true for methods because they don't have similar mechanism as classes. So basically this means that you will have to initialize EXPLICITLY each method variable.enter code here

like image 25
Leni Kirilov Avatar answered Oct 13 '22 20:10

Leni Kirilov