The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Local variable initialization - source: 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 "Local variable initialization - source:" Watch "Local variable initialization - source:" New topic

Local variable initialization - source:

Sridhar Gudipalli
Ranch Hand

Joined: Nov 02, 2005
Posts: 120
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.

Sridhar Gudipalli|SCJP 6.0
SCWCD objectives
wei luo

Joined: Jul 17, 2008
Posts: 14
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

Joined: Apr 05, 2009
Posts: 58
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

I love Mozart (^o^)
I agree. Here's the link:
subject: Local variable initialization - source:
It's not a secret anymore!