theTuxRacer theTuxRacer - 7 months ago 27
Java Question

Access object.variable in an array of objects

I need help with this piece of code.

public class ParkingLot {

static int MAX = 5;
static Car[] Slot = new Car[MAX];

public static void main(String[] args) {

Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");


public static void Allot() {
for (int i = 0; i <= Slot.length; i++) {


I am storing a
Object in
. I wish to print/access the
of the car stored in slot. How do I go about doing that?


Well, if car has a public property, or a public getter method (this is preferable - getNumber() and getColour()), you can call them while iterating the array with the for-each loop:

for (Car car : slot) {

Note that I've lowercased slot - variable names in Java should be lowercase. I'd also advise for naming the array with plural name - i.e. slots.

Note also that the way of iteration provided by others is possible, but not recommended for the basic case of iterating the whole array. Effective Java (Bloch) recommends using the foreach loop whenever possible.