Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Creating an Array of Objects in Java

In this lesson, you will learn

  • Array of Objects
  • Examples

 

Array of Objects

  • An array of objects in Java is use to store multiple instances of a class in an array where each element is a reference to an object of a particular class.
  • Instead of storing primitive data types (like int, float, char), it stores objects (instances of classes). This allows you to group and manage multiple objects of the same type in a structured way.

Let’s illustrate this with a Rectangle example and take input using the Scanner class:

Syntax

The below figure shows the structure and way to store multiple object in an array.

ArrayOfObjectsInJava

 

Example – Array of Objects

import java.util.Scanner;

class Rectangle {
    int length;
    int width;

    // Method to calculate area
    int calculateArea() {
        return length * width;
    }

    // Method to display rectangle dimensions
    void displayDimensions() {
        System.out.println("Length: " + length + ", Width: " + width);
    }
}

public class RectangleArray {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of rectangles: ");
        int numRectangles = scanner.nextInt();

        // Create an array of Rectangle objects
        Rectangle[] rectangles = new Rectangle[numRectangles];

        // Input dimensions for each rectangle
        for (int i = 0; i < numRectangles; i++) {
            rectangles[i] = new Rectangle(); // Important: Create each Rectangle object!
            System.out.println("Enter dimensions for rectangle " + (i + 1) + ":");
            System.out.print("Length: ");
            rectangles[i].length = scanner.nextInt();
            System.out.print("Width: ");
            rectangles[i].width = scanner.nextInt();
        }

        // Display dimensions and area of each rectangle
        System.out.println("\nRectangle Dimensions and Areas:");
        for (int i = 0; i < numRectangles; i++) {
            rectangles[i].displayDimensions();
            System.out.println("Area: " + rectangles[i].calculateArea());
            System.out.println("--------------------");
        }

        scanner.close(); // Close the scanner to release resources
    }
}


Output

Enter the number of rectangles: 3
Enter dimensions for rectangle 1:
Length: 5
Width: 6
Enter dimensions for rectangle 2:
Length: 10
Width: 20
Enter dimensions for rectangle 3:
Length: 7
Width: 8

Rectangle Dimensions and Areas:
Length: 5, Width: 6
Area: 30
--------------------
Length: 10, Width: 20
Area: 200
--------------------
Length: 7, Width: 8
Area: 56
--------------------


 

Some Exercises based on Array of Objects

Exercise 1: Student Management System

Create a program to manage student data. You should have a Student class with the following attributes:

  • name (String)
  • rollNumber (int)
  • grades (an array of integers to store grades for multiple subjects)

Implement the following functionalities:

  1. Input: Prompt the user to enter the number of students. Then, for each student, prompt for their name, roll number, and the number of subjects they have taken. Afterward, prompt the user to enter the grades for each subject for that student.

  2. Calculate Average: Add a method to the Student class to calculate the average grade for the student.

  3. Display: Display the information for each student, including their name, roll number, individual grades, and calculated average grade.

Example Interaction:

Enter the number of students: 2

Enter details for student 1:
Name: Alice
Roll Number: 123
Number of Subjects: 3
Enter grades for Alice:
Subject 1: 85
Subject 2: 92
Subject 3: 78

Enter details for student 2:
Name: Bob
Roll Number: 456
Number of Subjects: 2
Enter grades for Bob:
Subject 1: 90
Subject 2: 80

Student Information:
Name: Alice, Roll Number: 123
Grades: 85 92 78
Average Grade: 85.0
--------------------
Name: Bob, Roll Number: 456
Grades: 90 80
Average Grade: 85.0
--------------------

Exercise 2: Library Book Inventory

Create a program to manage a library’s book inventory. You should have a Book class with the following attributes:

  • title (String)
  • author (String)
  • isbn (String)
  • isBorrowed (boolean)

Implement the following functionalities:

  1. Add Books: Prompt the user to enter the number of books to add. Then, for each book, prompt for the title, author, and ISBN. Add these books to an array of Book objects.

  2. Borrow Book: Prompt the user to enter the ISBN of a book they want to borrow. Search the array of books. If the book is found and is not already borrowed, mark it as borrowed (isBorrowed = true). Otherwise, display a message that the book is not available.

  3. Return Book: Prompt the user to enter the ISBN of a book they want to return. Search the array. If the book is found and is currently borrowed, mark it as returned (isBorrowed = false). Otherwise, display a message that the book cannot be returned (e.g., if it was never borrowed or the ISBN is incorrect).

  4. Display Available Books: Display the title, author, and ISBN of all books that are currently available (not borrowed).

Example Interaction:

Enter the number of books to add: 3

Enter details for book 1:
Title: The Lord of the Rings
Author: J.R.R. Tolkien
ISBN: 978-0547928227

Enter details for book 2:
Title: Pride and Prejudice
Author: Jane Austen
ISBN: 978-0141439518

Enter details for book 3:
Title: 1984
Author: George Orwell
ISBN: 978-0451524935

Enter ISBN of book to borrow: 978-0141439518

Enter ISBN of book to return: 978-0141439518

Available Books:
Title: The Lord of the Rings, Author: J.R.R. Tolkien, ISBN: 978-0547928227
Title: Pride and Prejudice, Author: Jane Austen, ISBN: 978-0141439518
Title: 1984, Author: George Orwell, ISBN: 978-0451524935

These exercises will help you practice working with arrays of objects, creating classes, and implementing basic data management functionalities. Remember to handle user input appropriately and consider edge cases (e.g., invalid input, book not found).

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review