Welcome Guest | Sign in | Register
Objects and Collections - Discussion Page For Q.2905 | Java Programming Questions and Answers | Java Programming Free Online-Tests | LucentBlackBoard | LucentBlackBoard.com

Home > Java Programming > Objects and Collections > Questions and Answers

Exercise:

Section 1

Q: What will be the output of the program?
public class Test
{
private static int[] x;
public static void main(String[] args)
{
System.out.println(x[0]);
}
}
A. 0 B. null
C. Compile Error D. NullPointerException at runtime

Answer and Explanation

Answer:NullPointerException at runtime

Explanation:
In the above code the array reference variable x has been declared but it has not been instantiated i.e. the new statement is missing, for example:
private static int[]x = new int[5];
private static int[x] declares a static i.e. class level array.
the "new" keyword is the word that actually creates said array.
int[5] in association with the new sets the size of the array. so since the above code contains no new or size decalarations when you try and access x[0] you are trying to access a member of an array that has been declared but not intialized hence you get a NullPointerException at runtime.

Comment on this Question

Name:

Loading...




Partner Sites
LucentBlackBoard.com                  SoftLucent.com                  LucentJobs.com
All rights reserved © 2012-2015 SoftLucent.