Re: About Question enthuware.ocajp.i.v7.2.1404 :
Posted: Sun Apr 05, 2015 11:39 am
Hello,
I have a question regarding the first available optional answer for this topic, i.e int[][] a = new int[2][];
After the review, checking the answers, it says the above option is not correct because:
"This will instantiate only the first dimension of the array. The elements in the second dimension will be null. In other words, a will be instantiated to two elements but a[0] and a[1] will be null and so a[0][0] (and access to all other such ints) will throw a NullPointerException."
First question: Why would it throw a NullPointerException and why a[0] and a[1] would be null since they're declared as "int"? Wouldn't they be 0 instead?
However, I have tried it in Eclipse as I was not convinced by the above:
The below code runs smoothly:
import java.util.Arrays;
public class StringExercise {
public static void main(String args[]) {
int[][] a = new int[2][];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[1][2] = 5;
a[1][3] = 6;
}
}
Please correct me if this answer is not ok. According to me it should be right.
Please note that I ran this with the Java 8 installed. If this is the issue, please let me know if the above would be wrong in Java 7.
Any other explanations are welcomed by a beginner like me
Thanks
I have a question regarding the first available optional answer for this topic, i.e int[][] a = new int[2][];
After the review, checking the answers, it says the above option is not correct because:
"This will instantiate only the first dimension of the array. The elements in the second dimension will be null. In other words, a will be instantiated to two elements but a[0] and a[1] will be null and so a[0][0] (and access to all other such ints) will throw a NullPointerException."
First question: Why would it throw a NullPointerException and why a[0] and a[1] would be null since they're declared as "int"? Wouldn't they be 0 instead?
However, I have tried it in Eclipse as I was not convinced by the above:
The below code runs smoothly:
import java.util.Arrays;
public class StringExercise {
public static void main(String args[]) {
int[][] a = new int[2][];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[1][2] = 5;
a[1][3] = 6;
}
}
Please correct me if this answer is not ok. According to me it should be right.
Please note that I ran this with the Java 8 installed. If this is the issue, please let me know if the above would be wrong in Java 7.
Any other explanations are welcomed by a beginner like me
Thanks