Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize this 2D array with null in Java?

Tags:

java

arrays

null

I have made a 2-d array which will store references to objects of the children classes of parent class Student.

Student[][] a = new Student [5][4]; 

Now I want to initialize this array with null? How do I do it? Any trick to doing it at once? Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java?

I want to initialize all the values with null. Also, let's say some values are filled and then I want to overwrite the values with null. How do I do that?

like image 842
Harry Lewis Avatar asked Apr 21 '26 07:04

Harry Lewis


2 Answers

By default JAVA initialises the reference objects with null.

like image 81
Priyansh Goel Avatar answered Apr 23 '26 20:04

Priyansh Goel


There are three ways, choose the most priority for you.

Student[][] a = null; // reference to a equals null
Student[][] a = new Student[5][];  // {null, null, null, null, null}
Student[][] a = new Student[5][5];  // {{null, null, null, null, null}, {...}, ...}

For your purpose (from the comment), you could use Arrays.fill(Object[] a, Object val). For example,

for(Student[] array : a) Arrays.fill(array, null);

or

for(int i = 0; i < a.length; ++i)
    for(int j = 0; j < a[i].length; ++j)
        a[i][j] = null;

Also, I Wanted to know if it is possible to store references of children class in an array of Base class in Java?

Yes, that's possible. The process named upcasting (SubStudent is upcasted to Student).

a[0][0] = new SubStudent();
a[0][1] = new Student();
like image 32
Andrew Tobilko Avatar answered Apr 23 '26 20:04

Andrew Tobilko