Arrays of Objects in Java

dallington256

Dallington Asingwire

Posted on October 20, 2021

Arrays of Objects in Java

An array is a collection of items or elements of the same data type placed in a contiguous memory location that can accessed using a unique index.
An object is an instance of a class. so basically, an array of objects is a container of objects collected in an array. Unlike a traditional array that stores values of the same primitive data type like integer, string, boolean, etc., an array of objects stores objects.
Note that an object can have properties with values of different data types.
Example: In a bank setting, you can have an array of customer data that has customer details as objects for example customer details object may have name of the customer, date of birth, account number, account balance, address etc.

Code: Now let's see how to map this example into code.


public class Customer{
    String name, dob, account_no, address;
    double account_balance;
    public Customer(String name, String dob, String acc_no, 
             double balance, String address){
        this.name = name;
        this.dob = dob;
        this.account_no = acc_no;
        this.account_balance = balance;
        this.address = address;
   } 

 @Override
public String toString(){
 return "Customer{Name="+ name + ","
        + " Date of birth="+ dob + ","
            + " Account Number="+ account_no + ","
        + "  Balance="+ account_balance + ","
        + "  Address="+ address + "}";
}
}

public class Bank{
public static void main(String[] args){

// Customer objects
   Customer c1 = new Customer("Dallington", "16-11-1986", 
                              "43555514145", 660000, 
                              "Kampala");
   Customer c2 = new Customer("John", "09-07-1998", 
                              "43555514628", 21000, 
                              "Mbarara");
   Customer c3 = new Customer("Fylnor","15-07-2000", 
                              "43555514001", 780000, 
                              "Bushenyi");

// Array of customers (Array of customer objects)
    Customer[] customers = new Customer[3];
    customers[0] = c1;
    customers[1] = c2;
    customers[2] = c3;

// Printing the array objects
      for(Customer c: customers){
           System.out.println(c);
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

And that's how the concept of array of objects is implemented in java.
Hope you can make use of this concept in your programming practices or complex projects.
Thank you for taking time to read through this post.

đź’– đź’Ş đź™… đźš©
dallington256
Dallington Asingwire

Posted on October 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related