• 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
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Doubt  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a question in mock exam like

public class test
{
private static int[]x;
public static void main(String a[])
{
System.out.println(x[0]);
}
}

I didn't understand why the answer of this is NullPointerException.
Plz explain......

Thanks
UmaVinodh.
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array is an object.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To elaborate:

Although we know, Array elements are always given default values, regardless of where the array itself is declared or instantiated.

In your code, the array is declared, not instantiated. Moreover, since x is an object, it is not yet existing to be called.

If you replace your array declaration with an instantiation as well:
private static int[] x = new int[5];

you will get your expected "0" output.
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initial Values of Variables.
 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because You wany to print the value before initializing array object. Thats it.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a subtle terminology:
Array objects are automatically initialized with default values.

What's missing here is "instantiation" not initialisation.
 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array elements get their defualt value when array is initialized.
when we declare array i.e. int [] x; it is null a this moment. When we say
x = new int [6]; now all the 6 elements of array will get thier defualt value
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!