In Java, an array is a data structure that stores a fixed number of values of the same data type. For example, if you want to store information about several cars, you could use an array of car objects.
java code for array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Car { String make; String model; int year; // constructor and other methods } class Main { public static void main(String[] args) { Car[] cars = new Car[3]; cars[0] = new Car("Toyota", "Camry", 2020); cars[1] = new Car("Honda", "Accord", 2019); cars[2] = new Car("Tesla", "Model 3", 2018); for (int i = 0; i < cars.length; i++) { System.out.println("Car " + (i + 1) + ": " + cars[i].make + " " + cars[i].model + " " + cars[i].year); } } } |
This code defines a Car
class with three instance variables (make
, model
, and year
), a constructor, and possibly other methods. The Main
class creates an array of three Car
objects and initializes each element with information about a different car. Finally, it prints out information about each car using a for
loop.
This is just one example of how you can use arrays in Java to store and manipulate collections of data. Arrays are a powerful tool that can make your code more concise and readable, especially when working with large amounts of similar data.
Output:
Car 1: Toyota Camry 2020
Car 2: Honda Accord 2019
Car 3: Tesla Model 3 2018