• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!