Java Programming - Objects and Collections - Discussion
Discussion Forum : Objects and Collections - Finding the output (Q.No. 4)
4.
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]);
}
}
Answer: Option
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.
Discussion:
3 comments Page 1 of 1.
Vaijeyanthi said:
9 years ago
Yes, it is declared exceptionally.
Rajesh Kushwaha said:
1 decade ago
At this line : private static int[]x only reference variable is declared. No size of this array is declared.
And on Run Time : System.out.println(x[0]);
We are accessing 0th position of this array index value. But no any value or size declared or initialized above so NullPointerException at runtime occur.
And on Run Time : System.out.println(x[0]);
We are accessing 0th position of this array index value. But no any value or size declared or initialized above so NullPointerException at runtime occur.
Ignacius said:
1 decade ago
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:6)
at Main.main(Main.java:6)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers