1

I find the new operator a bit confusing. My understanding now is that

new ClassName(...)

is to make an instance and call the Class' constructor. But what does new do when initiating an Array? For example, I feel the two new operators below are different, but can't explain clearly.

Employee[] staff = new Employee[3];
staff[0] = new Employee(...);

Are there any difference?

Thanks.

2
  • 1
    staff[0] is a reference to your Employee object. Commented Jan 23, 2015 at 17:25
  • They're exactly the same.. staff[0] is of type Employee. Commented Jan 23, 2015 at 17:26

3 Answers 3

4

new Employee[3] creates an array that can hold references to 3 Employee instances. Each of them is initialized to null. staff[0] = new Employee(...); creates an Employee instance and assigns its reference to the first index of the array.

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

Comments

3
Employee[] staff = new Employee[3];

Is initializing your array of Employees with 3 "places" which can hold references to your Employee objects.
That means it reserves 3 times the space needed for one object/instance of your Employee class (e.g. 10byte) in the RAM (=> 30 byte).
But your array is initalized with "null". While staff[0] = new Employee(...); is creating a reference to your newly created object of type Employee. arrays

2 Comments

Thanks. Does "new Employee[3]" reserve place for 3 references (kind of a C pointer?) or actually space for 3 Employee objects (but not actually creating them) ?
You're welcome. The system (Java Virtual Machine) allocates the memory needed for 3 Employees, not just the references. E.g. int[] arr = new int[10]; // allocates memory for 10 integers For more info: docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
1

When you call the class' constructor, an instance (object) of that class is created. The "new" keyword is what tells the compiler to create an object. An array is a class and you make objects of type Array of SomeClass. You need to use the keyword "new" because you are still creating an object.

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.