This week's book giveaways are in the Scala and Android forums.
We're giving away four copies each of Machine Learning Systems: Designs that scale and Xamarin in Action: Creating native cross-platform mobile apps and have the authors on-line!
See this thread and this one for details.
Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple variable initialization ques  RSS feed

 
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
 
Ranch Hand
Posts: 10128
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
 
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.
 
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
 
Brace yourself while corporate america tries to sell us its things. Some day they will chill and use tiny ads.
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!