File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple variable initialization ques

 
Nikhil Bansal
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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];

System.out.println(arr[0]);

}

}

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

Regards

Nikhil Bansal
 
Joe Harry
Ranch Hand
Posts: 10045
3
Eclipse IDE Mac PPC Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Regards,
Jothi Shankar Kumar. S
 
Jae Stryker
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As above, this I believe is only applicable to Arrays of primitives.
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys for your inputs.

Regards

Nikhil Bansal
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic