cupojava
cupojava

Reputation: 79

Java - Initial value of an array of objects

in Java, what is the initial value inside an array. For instance,

My complete code:

public class Job{
    public Job(){
        String jobTitle = "";
    }//end constructor

    Job[] x = new Job[20];

}//end Job class

What is inside x array, at index 0, 1, 2...etc.? Is every index filled with an empty string named jobTitle? Also, is this an array of Objects? Specifically Job objects?

Upvotes: 1

Views: 577

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280030

Each index in an array references null until it is initialized to another value.

So

Job[] jobs = new Job[2];

will hold 2 Job references, but they will both be null. That is until you initialize them

jobs[0] = new Job();
jobs[1] = new Job();

Note that in this case, you've declared x as an instance field of Job, so each new Job object you create will have a Job array with 20 null Job references.

Upvotes: 2

Mark Elliot
Mark Elliot

Reputation: 77054

x is an array of 20 Job objects, all of which are initialized to null. If you want to initialize each one to be a new object you can use a for loop:

for (int i = 0; i < x.length; i++) {
    x[i] = new Job();
}

Upvotes: 4

Related Questions