[java] Returning Arrays in Java

I have absolutely no idea as to why this code won't return an array... I feel like there is a problem with my compiler:

public class trial1{

    public static void main(String[] args){
        numbers();
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

The code returns nothing at all. It's driving me crazy!

This question is related to java

The answer is


If you want to use the numbers method, you need an int array to store the returned value.

public static void main(String[] args){
    int[] someNumbers = numbers();
    //do whatever you want with them...
    System.out.println(Arrays.toString(someNumbers));
}

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...


You need to do something with the return value...

import java.util.Arrays;

public class trial1{

    public static void main(String[] args){
        int[] B = numbers();
        System.out.println(Arrays.toString(B));
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}

Of course the method numbers() returns an array, it's just that you're doing nothing with it. Try this in main():

int[] array = numbers();                    // obtain the array
System.out.println(Arrays.toString(array)); // now print it

That will show the array in the console.


As Luiggi mentioned you need to change your main to:

import java.util.Arrays;

public class trial1{

    public static void main(String[] args){
        int[] A = numbers();
        System.out.println(Arrays.toString(A)); //Might require import of util.Arrays
    }

    public static int[] numbers(){
        int[] A = {1,2,3};
        return A;
    }
}