We know that out of local variables if no initialization is provided, a default initialization takes place at the time of class loading or instantiation. :icon_rolleyes:But the question is where it takes place in a programming code? Either it is after the declaration then and there to protect and optimise the memory allocated for the variable or it is before any assignment operation:icon_question:
e.g. in the code fragment int i; i+=2; here i gets the default int value 0
whereas in the loop condition of

int i,j; for(j=100;i<j;j--){i+=2;}

i remains uninitialized:icon_exclaim:

If you provide no explicit initialization to instance variables, they will be given default initial values, which are based only on the type of the variable (zero, false or null as appropriate). Local variables are not given default initial values. They must be initialized explicitly before they are used.

The question "where in the code" is a bit if a false question. The default values are established before the execution of any code that uses them - it's time sequence not a place.

In your second example you say "i remains uninitialised". How do you know? You haven't tried to use its value. If you tried you would find it was initialised (assuming its not a local variable). What is the sound of one hand clapping?


To add to the other post-- it is also a bad programming habit to rely on default initialization. You should initialize yourself when you declare or make damn sure the variables are initialized before using them.

You can refer to the book, "Code Complete" for many style tips.

e.g. in the code fragment int i; i+=2; here i gets the default int value 0

Um, no it doesn't. Not unless it's a field.

int i,j; for(j=100;i<j;j--){i+=2;}

This won't compile, either. Did you try these before you posted this?

What is the sound of one hand clapping?

I believe you can hear that as the percussion part to John Cage's 4'33"

This article has been dead for over six months. Start a new discussion instead.