• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt

 
Uma Vinodh
Greenhorn
Posts: 28
  • 0
  • 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.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Array is an object.
 
Amieya Prabhaker
Ranch Hand
Posts: 45
  • 0
  • 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.
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Initial Values of Variables.
 
Rushikesh Wagh
Ranch Hand
Posts: 58
  • 0
  • 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
  • 0
  • 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.
 
Amirr Rafique
Ranch Hand
Posts: 324
  • 0
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic