• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple variable initialization ques

 
Nikhil Bansal
Ranch Hand
Posts: 60
  • 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: 10112
3
Eclipse IDE Mac PPC Ubuntu
  • 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
  • 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
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys for your inputs.

Regards

Nikhil Bansal
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic