Author Topic:   init String arrays in code blocks/methods
Nalini Mistry
ranch hand
posted March 23, 2000 12:54 AM             
class var are given a default init value if not explicitly init. local var within methods/code blocks are not. OKAY given this rule, what about arrays??

String[] s = new String[10];

when this is declared in a class it is init by default with null at this point. but does it hold true within code blocks/methods??

veena
unregistered
posted March 23, 2000 03:18 AM           
arrays are always initialized with default values when it is created whether it is defined locally or in class

maha anna
bartender
posted March 23, 2000 07:25 AM             
Nalini,
The important point to understand in case of arrays is,
1. When you allocate memory for a array either by means of new operator or by declaring and initializing at the same statement like String[] s = {"I", "like","Java"}; all elements of the array are set to their default value according to the type of the array. There is no doubt in that whether it is a class member/instance member/local method var/local block var. But when you just declare it without initializing the reference var , then the qstn arises. When it is a class/instance member the reference is set to null. But for local declaration of arrays inside methods/blocks you have to specifically set to null. Otherwise when you try to access the ref var before initializing it inside methods/blocks the compiler complains. There comes the diference. Follow the code below. you will know the the difference.
regds
maha anna

class Test {
String[] s;
{
System.out.println(s); //prints out null
}
void m1() {
String[] s;
System.out.println(s); //you can't do this. s will not be set to null.
}
public static void main(String[] args) {
new Test();
}
}


Nalini Mistry
ranch hand
posted March 25, 2000 12:40 PM             
Thanx anna

|