Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local variable initialization - source: http://www.jchq.net/mockexams/exam1.htm

 
Sridhar Gudipalli
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was working on Q10 and I got a doubt:

public class Q {
public static void main(String argv[]){
int anar[]=new int[5]; //line 1
System.out.println(anar[0]); //line 2
}
}

It prints "0" without initialization of the array.
However, If I replace the line 1 and line 2 with the below code, its gives the compilation error.

int anInt; //line 1
System.out.println(anInt); //line 2

I understood the error message: "The local variable anInt may not have been initialized".

Can somebody explain the reason behind allowing to access uninitialized array but not uninitialized int?

Thanks for your time.

 
wei luo
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the Array Object will be initialized no matter where it is declared ( as method local or instance or class variable), and the default value is the default of the type
 
yen hoang
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a rule for array elements you should remember:
Array elements are always, always, always given default values, regardless of where the array itself is declared or instantiated
Have fun and good luck
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic