aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Initialization" Watch "Array Initialization" New topic
Author

Array Initialization

Snigdha Solanki
Ranch Hand

Joined: Sep 07, 2000
Posts: 128
This is a question from A Programmer's Guide to Java Certification by Mughal
class MyClass{
public static void main(String args[]){
int size = 30;
int[] arr = new int[size];
for(int i=0;i< size;i++){
System.out.println(arr[i]);
}
}
}
a) Code will fail to compile because int array declaration is wrong
b)The program will compile but will throw an IndexArrayOutOfBounds Exception when run.
c)The program will compile and run without error ,but will produce no output
d) The program will compile and run without error and type nos 0 to 19.
e) The program will compile and run without error and type twenty 0s.
f)The program will compile and run without error and type twenty nulls.
The answer given is (e), But isn't array a local variable so by default it should not be initialized to anything?And accessing elements from an uninitialized array should give run time exception.


Snigdha<br />Sun Certified Programmer for the Java™ 2 Platform
Amandeep Waraich
Ranch Hand

Joined: Jul 14, 2000
Posts: 56
Hi,
The array elements are initialized irrespective of the scope of the array variable (arr). What you are confusing this with is that, if arr had not been initialized, then it would automatically be initialized if it was a member variable, and you would get an error if arr was a local variable. If arr is initialized, its elements are automatically initialized, irrespective of whether it is a member or a local variable.
-Aman
[This message has been edited by Amandeep Waraich (edited September 07, 2000).]
SathishVJ
Greenhorn

Joined: Sep 07, 2000
Posts: 16
Hi Aman,
If we take the code you have given verbatim, then none of the answers are right. Assuming the value of size is 20 then ans e is indeed right.
The J Lang Specs says


Sec: 10.3 Array Creation
An array initializer creates an array and provides initial values for all its components.


(even if they are local variables).
I don't know if what I am assuming henceforth is right, but I guess that the values the array elements are initialized with will be the values they will be assigned in case they were class variables.
i.e. null for all derivatives of Object, false for boolean and 0 for the numeric types.
Regards
Sathish
Snigdha Solanki
Ranch Hand

Joined: Sep 07, 2000
Posts: 128
Thanks Aman for the explanation
 
Consider Paul's rocket mass heater.
 
subject: Array Initialization