3

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?

1
  • can you give an example of what you want to do? Student[][] a = null; ? You have to be more precise. you probably want to initialse all values in the array with null, which would be done with nested for-loops. Commented May 28, 2016 at 13:05

2 Answers 2

5

By default JAVA initialises the reference objects with null.

Sign up to request clarification or add additional context in comments.

Comments

5

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();

2 Comments

if I fill the array with some values, and then if I want to overwrite the values in the entire array with NULL, then also I can use the above method?
@HarryLewis, I showed to you ways of initialization, if you want to change all values in the array, you may use Arrays,fill or a[i][j] = null in for loops manually

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.