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


What purpose does it work?

Just read an example in that book where the author has done this.

Integer number = 0; Automatic assignment to zero applies to members only, not for local variables

If this is a local variable and if = 0 is omitted, then that variable has no value, not even zero. Attempting to use the value before the value is specified will result in a compilation error. For example, this code tries to use an unused local variable:

  public class program {public static zero main (string [] args) {int numOfGuesses; // local variable system.out.println (numOfGuesses); }}  

and this compile error produces:

  program. Java: 6: variable numOfGuesses can not start System.out.println (numOfGuesses);  

Using a member, this code zero and outputs:

  the public class program {int numOfGuesses; // Member Variable Public Futile Run () {System.out.println (numOfGuesses); } Public static zero main (string [] args) {new program (). Run (); }}  

For members I assign zero for explicilty if my code uses the fact that the initial zalue is zero, and leave the assignment if my code is of the initial value For example if this value is assigned in the constructor or elsewhere). The result is similar, so it's just a style issue.


Comments