[java] How do you declare an object array in Java?

Possible Duplicate:
How to declare an array in Java?

Suppose I have an object car (class vehicle) and I want to create an array of N number of cars . How do I declare that in Java?

vehicle[N]= car=new vehicle [];

Is this right?

This question is related to java arrays

The answer is


It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.


vehicle[] car = new vehicle[N];

Like this

Vehicle[] car = new Vehicle[10];


This is the correct way:

You should declare the length of the array after "="

Veicle[] cars = new Veicle[N];