Returning an array without assign to a variable

JavaArrays

Java Problem Overview


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};
}
    

Java Solutions


Solution 1 - Java

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 {}.

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

return new Integer[] {a,b,c,d}; // or
return new int[] {a,b,c,d};

Solution 5 - Java

public class CentsToDollars {
	
    public static int[] getCentsToDollars(int cents) {
		return new int[] { cents / 100, cents % 100 };
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int cents;
		System.out.print("Input the cents: ");
		cents = scan.nextInt();
		int[] result = getCentsToDollars(cents);
		System.out.println("That is " + result[0] + " dollars and " + result[1] + " cents");
		scan.close();
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlejandro GarciaView Question on Stackoverflow
Solution 1 - JavaPerceptionView Answer on Stackoverflow
Solution 2 - JavagaryamorrisView Answer on Stackoverflow
Solution 3 - Javae-zincView Answer on Stackoverflow
Solution 4 - JavaSivasubramaniam ArunachalamView Answer on Stackoverflow
Solution 5 - JavaKinoweView Answer on Stackoverflow