Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Returning an Array of Object from a Method in Java

In this lesson, you will learn

  • Returning an Array of Objects from a Method in Java
  • Example

 

Returning an Array of Objects from a Method

  • Returning an array of objects from a method in Java is a common practice, especially when you need to work with multiple instances of a class at once.

 

Example 1: Returning an Array of Objects from a Method

package ch7.l7;

class Rectangle {
    int width;
    int height;

    // Constructor to initialize dimensions
    public Rectangle(int w, int h) {
        width = w;
        height = h;
    }
    
    // Method to generate and return an array of Rectangle objects
    public static Rectangle[] generateRectangles(int numOfRect) {
        Rectangle[] rectangles = new Rectangle[numOfRect];

        for (int i = 0; i < numOfRect; i++) {
            // For example, create rectangles with increasing dimensions
            rectangles[i] = new Rectangle(i + 1, (i + 1) * 2);
        }
        
        return rectangles;
    }
}

public class RectangleArrayGenerator {
	public static void main(String[] args) {
        // Generate an array of 5 Rectangle objects
        Rectangle[] rectangles = Rectangle.generateRectangles(5);

        // Iterate over the array and print the dimensions of each rectangle
        for (Rectangle rect : rectangles) {
            System.out.println("Rectangle dimensions: " 
            		+rect.width + "x" + rect.height);
        }
    }
}

Output

Rectangle dimensions: 1x2
Rectangle dimensions: 2x4
Rectangle dimensions: 3x6
Rectangle dimensions: 4x8
Rectangle dimensions: 5x10

 

Explanation

In this example, the Rectangle class contains a static method generateRectangles that takes an integer numbOfRect as its parameter.

This method initializes an array of Rectangle objects of the specified size, fills the array with Rectangle instances (in this case, with incrementing dimensions), and then returns the array.

This approach demonstrates how to encapsulate the creation of multiple instances of a class in a single method, providing a clean and efficient way to generate and work with collections of objects in Java.

 

 


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