Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Initialization

 
Snigdha Solanki
Ranch Hand
Posts: 128
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Amandeep Waraich
Ranch Hand
Posts: 56
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 128
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Aman for the explanation
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic