File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt" Watch "Doubt" New topic


Uma Vinodh

Joined: Apr 26, 2006
Posts: 28
There is a question in mock exam like

public class test
private static int[]x;
public static void main(String a[])

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

Amieya Prabhaker
Ranch Hand

Joined: Apr 23, 2006
Posts: 45
Array is an object.
Amieya Prabhaker
Ranch Hand

Joined: Apr 23, 2006
Posts: 45
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

Joined: Feb 02, 2006
Posts: 2023
Initial Values of Variables.
Rushikesh Wagh
Ranch Hand

Joined: Jun 18, 2005
Posts: 58
Because You wany to print the value before initializing array object. Thats it.

Best Regards,
Rushikesh Wagh
SCJP 1.4 (2005)
SCJP 1.6 (2010)
Amieya Prabhaker
Ranch Hand

Joined: Apr 23, 2006
Posts: 45
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

Joined: Nov 14, 2005
Posts: 324
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

"Know where to find the solution and how to use it - that's the secret of success."
I agree. Here's the link:
subject: Doubt
It's not a secret anymore!