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}; }
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.
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.
So, no. You can't avoid "initializing" an array.
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 {}
.
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
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