Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Arrays in Java [closed]

Tags:

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!

like image 625
Atreyu Avatar asked Oct 13 '12 03:10

Atreyu


People also ask

Can you return arrays in Java?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.

How can I return two arrays from a method in Java?

Ideally, you should split the computation and return of the arrays into their own method. If the int/String arrays represent key/value pairs, then use can use a Map DST implementation (http://download.oracle.com/javase/6/docs/api/java/util/Map.html) instead and return that. You can iterate over key/values as necessary.


2 Answers

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {     {1,2,3}; } 

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){     int[] result = numbers();     for (int i=0; i<result.length; i++) {         System.out.print(result[i]+" ");     } } 
like image 141
AlexFZ Avatar answered Oct 21 '22 00:10

AlexFZ


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.

like image 22
Óscar López Avatar answered Oct 21 '22 01:10

Óscar López