• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

init String arrays in code blocks/methods

 
Nalini Mistry
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 devi
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
arrays are always initialized with default values when it is created whether it is defined locally or in class
 
maha anna
Ranch Hand
Posts: 1467
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
<pre>
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();
}
}
</pre>
 
Nalini Mistry
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx anna
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic