1

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?

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Just so I understand, this is putting inside each array index the empty String jobTitle? (I'm not sure if I'm asking this properly...). EDIT: by putting inside I mean, each array index is now a Job object which contains the empty string jobTitle.
@cupojava: this puts an instance of Job in each index. Your constructor will create an instance of String jobTitle that's given the empty string value for each object creation, but the instance of String is not saved since you don't hang on to the reference outside of your constructor.
Strings are auto-initialized to null, so if I'm understanding you correctly, the 'String' instance in each of the array indices is now null?
No, you're explicitly initializing your String jobTitle by setting it to the empty string (also written "").
2

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.

Comments

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.