Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes init String arrays in code blocks/methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "init String arrays in code blocks/methods" Watch "init String arrays in code blocks/methods" New topic
Author

init String arrays in code blocks/methods

Nalini Mistry
Ranch Hand

Joined: Mar 21, 2000
Posts: 64
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

Joined: Aug 25, 2003
Posts: 18
arrays are always initialized with default values when it is created whether it is defined locally or in class
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
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

Joined: Mar 21, 2000
Posts: 64
Thanx anna
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: init String arrays in code blocks/methods
 
Similar Threads
forward referencing
Extending javafx.animation.KeyValue public-init override problem
Initialiser
final variable