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!
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.
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.
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]+" "); } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With