How to return an array in Java


Array JavaViews 6122

In previous articles, we have seen how we can return a value from a method in Java. There are situations where we need to return multiple values or an array from a function. This tutorial will guide you on how to return an array in Java of various data types.

How to return an array in Java

Return an array of integer values

In the below program, we will learn how to return an array of integer values from a method in Java. We have a method getValues() that returns an array of Integer values. Whenever a method returns a value, the method definition must have the same return type. In this case, since it is an array of integer values, we define return type as int[]. Within a method, we can return values using the return keyword.

Similarly, from the calling method, when we invoke the method, it needs to assign the values to an array. Hence we declare int[] arrData that accepts the array values passed from the getValues() method. Now we can access the individual values using the array index within a for loop. This example also shows how to calculate the sum of all integer values that we retrieve from an array.

public class ReturnArrayInt {

  public static void main(String[] args) {
    int[] arrData = getValues();
    int sum = 0;
    
    System.out.println("Array values:");
    for(int i=0;i<arrData.length;i++) {
      System.out.print(arrData[i] + " ");
    }
    
    for(int i=0;i<arrData.length;i++) {
      sum = sum + arrData[i];
    }
      
    System.out.println("\nSum of array values: " + sum);

  }

  public static int[] getValues() {
    int[] arrValues = {10,20,30,40};
    return arrValues;
  }
}
Array values:
10 20 30 40 
Sum of array values: 100

Return an array of double values

We can return an array of any data type from a method. The below code shows how to return an array of double data types in Java. The getWeight() method returns an array of double values. In the main method, we implement logic to compare and classify the array weight double values as “Underweight” or “Normal weight” or “Overweight”. We can retrieve each double array value using an enhanced for loop.

public class ReturnArrayDouble {

  public static void main(String[] args) {
    double[] arrValue = getWeight();
    System.out.println("Array double values:");
    double normalwt = 55;
    double overweight = 80;
    
    for(double d: arrValue) {
      if(d < normalwt)
        System.out.println(d + " : Underweight");
      else if(d > normalwt && d < overweight)
        System.out.println(d + " : Normal weight");
      else
        System.out.println(d + " : Overweight");
    }
  }
  
  public static double[] getWeight() {
    double[] arrWt = {34.5,55.6,80.4,25.5};
    return arrWt;
  }

}
Array double values:
34.5 : Low weight
55.6 : Normal weight
80.4 : Over weight
25.5 : Low weight

Return an array of String values

The below code shows how to return an array of String values from a method in Java.

public class ReturnArrString {

  public static void main(String[] args) {
    String[] arrValues = getNames();
    System.out.println("Array String values:");
    
    for(String names: arrValues)
      System.out.println(names);

  }
  
  public static String[] getNames() {
    String[] arrNames = {"Hari","Dev","Jay","Kumar","Raju"};
    return arrNames;
    }

}
Array String values:
Hari
Dev
Jay
Kumar
Raju

Return an array of objects

The below example shows how to return an array of objects from a method in Java. We create a class Employee that has a constructor to initialize empName and empId values. From the main class, we have a getEmployees() method where we create 2 Employee objects and return this array of Employee objects. Hence the method definition must also have a return type as an Employee array. From the main method, we can retrieve the empName and empId values using the Employee object within an enhanced for loop.

class Employee {
  String empName;
  int empId;
  
  Employee(String empName, int empId){
    this.empName = empName;
    this.empId = empId;
  }
}

public class ReturnArrayObj {

  public static void main(String[] args) {
    Employee[] arrNames = getEmployees();
    
    for(Employee e : arrNames)
      System.out.println("EmpName: " + e.empName + " EmpID: " + e.empId);

  }
  
  public static Employee[] getEmployees() {
    Employee[] arrEmp = new Employee[2];
    arrEmp[0] = new Employee("Rohit",345123);
    arrEmp[1] = new Employee("Vishal",556998);
    
    return arrEmp;
  }

}
EmpName: Rohit EmpID: 345123
EmpName: Vishal EmpID: 556998

Return an array and pass an array as an argument

It is also possible to pass an array as an argument to a method and return an array of String values from a method in Java. The method sortNames() contains an array of String values as an argument and also returns an array of String values. This method sorts the Names in ascending order and returns an array of String values in the ascending order.

import java.util.Arrays;

public class ReturnArrString {

  public static void main(String[] args) {
    String[] arrNames = {"Hari","Dev","Raju","Jay"};
    String[] arrValues = sortNames(arrNames);
    System.out.println("Sorted Array String values:");
    
    for(String names: arrValues)
      System.out.println(names);

  }
  
  public static String[] sortNames(String[] arrNames) {
    String temp;
    int len = arrNames.length;
    
    for(int i=0;i<len-1;i++) {
      for(int j=i+1;j<len;j++) {
        if(arrNames[i].compareTo(arrNames[j]) > 0){
          temp = arrNames[i];
          arrNames[i] = arrNames[j];
          arrNames[j] = temp;
        }
      }
    }
    return arrNames;
    }

}
Sorted Array String values:
Dev
Hari
Jay
Raju

Return a 2D array from a method

Return a 2D array from a method

A 2-dimensional array consists of 2 rows and 2 columns. The below example shows how to return a 2D array from a method in Java. The class createArray contains a method ArrayCreation() that creates a 2-d array and returns a 2D array.

public class Return2DArray {

  public static void main(String[] args) {
    createArray c = new createArray();
    int[][] arrData = c.ArrayCreation();
    System.out.println("Array values");

    for(int i=0;i<2;i++) {
      for(int j=0;j<2;j++)
        System.out.print(arrData[i][j] + " ");
      System.out.println();
    }
  }

}

class createArray {
  public int[][] ArrayCreation(){
    int[][] a = new int[2][2];
    for(int i=0;i<2;i++) {
      for(int j=0;j<2;j++) {
        a[i][j] = i+1;
      }
    }
    return a;
  }
  
}
Array values
1 1 
2 2 

Return a 3D array from a method

Return a 3D array from a method

We can also return a 3-dimensional array from a method in Java that contains 3 rows and 3 columns. The below example illustrates the same.

public class Return3DArray {

  public static void main(String[] args) {
    createArray c = new createArray();
    int[][] arrData = c.ArrayCreation();
    System.out.println("Array values");

    for(int i=0;i<3;i++) {
      for(int j=0;j<3;j++)
        System.out.print(arrData[i][j] + " ");
      System.out.println();
    }
  }

}

class createArray {
  public int[][] ArrayCreation(){
    int[][] a = new int[3][3];
    for(int i=0;i<3;i++) {
      for(int j=0;j<3;j++) {
        a[i][j] = i+1;
      }
    }
    return a;
  }
  
}
Array values
1 1 1 
2 2 2 
3 3 3 

 

Reference

Translate ยป