File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Simple variable initialization  ques 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 "Simple variable initialization  ques" Watch "Simple variable initialization  ques" New topic

Simple variable initialization ques

Nikhil Bansal
Ranch Hand

Joined: Jan 24, 2005
Posts: 60
Hi All,

A simple question about initialization of the variable.What will be the output of the foll. program.

class Test {

public static void main(String args[]) {

int arr[] = new int[2];




I expect a compiler -error since the array variable (which is local) has not been initialized.


Nikhil Bansal

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10032

Hi Nikhil,

There is an exception to arrays that whereever they are declared (local or instance), they get their default values. So the program shud print 0 since it is an int array.

Jothi Shankar Kumar. S

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Jae Stryker

Joined: Oct 31, 2006
Posts: 21
As above, this I believe is only applicable to Arrays of primitives.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
As soon as the array is created using this form of array creation statement, its elements are automatically initialized to their default values.

String[] str = new String[6]; // fill default value null into elements
Nikhil Bansal
Ranch Hand

Joined: Jan 24, 2005
Posts: 60
Thanks guys for your inputs.


Nikhil Bansal
I agree. Here's the link:
subject: Simple variable initialization ques
It's not a secret anymore!