logo

Javaで配列を返す方法

このセクションでは、Java で配列を返す方法を学習します。

覚えて:

  • メソッドは配列への参照を返すことができます。
  • メソッドの戻り値の型は、正しいデータ型の配列として宣言する必要があります。

例1

次の例では、メソッドは整数型の配列を返します。

forループJava
 import java.util.Arrays; public class ReturnArrayExample1 { public static void main(String args[]) { int[] a=numbers(); //obtain the array for (int i = 0; i <a.length; i++) for loop to print the array system.out.print( a[i]+ ' '); } public static int[] numbers() { arr="{5,6,7,8,9};" initializing return arr; < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java.webp" alt="How to return an array in Java"> <h3>Example 2</h3> <p>In the following example, the method returns an array of double type. </p> <pre> public class ReturnArrayExample3 { public static double[] returnArray( ) { double[] arr = new double [3]; // Creating an array of 3 elements arr[0]=6.9; arr [1]=2.5; arr [2]=11.5; return( x ); // Return the reference of the array } public static void main(String[] args) { double[] a; //variable to store returned array a = returnArray(); //called method for (int i = 0; i <a.length; i++) for loop to print the array system.out.println( a[i]+ ' '); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java-2.webp" alt="How to return an array in Java"> <h3>Example 3</h3> <p>In the following example, method returns an array of object type.</p> <pre> import java.util.Arrays; class ReturnArrayExample3 { public static int[] returnArray() { int a1=20; int a2=23; int a3=87; return new int[] {a1,a2,a3}; //returns array } public static void main(String args[]) { int[] arr=returnArray(); //invoking method and storing returned array into arr System.out.println(Arrays.toString(arr)); //returns the string representation of the object } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java-3.webp" alt="How to return an array in Java"> <hr></a.length;></pre></a.length;>

出力:

Javaで配列を返す方法