Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an array without assign to a variable

Tags:

java

arrays

Is there any way in java to return a new array without assigning it first to a variable? Here is an example:

public class Data {     private int a;     private int b;     private int c;     private int d;     public int[] getData() {         int[] data = { a, b, c, d };         return data;     } } 

I want to do something like this, but doesn't work:

public int[] getData() {     return {a, b, c, d}; } 
like image 244
Alejandro Garcia Avatar asked Feb 17 '12 16:02

Alejandro Garcia


People also ask

What happens if we declare an array without assigning the size?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.

Can a method return an array?

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.

Can we declare array without initialization?

So, no. You can't avoid "initializing" an array.


2 Answers

You still need to create the array, even if you do not assign it to a variable. Try this:

public int[] getData() {     return new int[] {a,b,c,d}; } 

Your code sample did not work because the compiler, for one thing, still needs to know what type you are attempting to create via static initialization {}.

like image 131
Perception Avatar answered Sep 20 '22 17:09

Perception


You been to construct the object that the function is returning, the following should solve your issue.

public int[] getData() {     return new int[]{a,b,c,d}; } 

hope this helps

like image 37
garyamorris Avatar answered Sep 18 '22 17:09

garyamorris