1

I am trying to declare an int array in the call of a method, is this possible in Java?

I am relatively new to Java but have some python knowledge. I was trying to find an equivalent of (in python3):

foo([1,2,3,4])  #python

Declaring the array first works ofc:

int[] data = {1,2,3,4,5};
printArray(reverseArray(data));

But I was wondering if something such as:

printArray(reverseArray(int[] {1,2,3,4,5}));

Was possible.

I am working under Netbeans and my above attempted solution is reported as a 'not a statement' error. Also, would:

int[] data = new int[] {1,2,3,4,5} 

be more correct than simply:

int[] data = {1,2,3,4,5};

?

A.D
  • 427
  • 1
  • 4
  • 12

2 Answers2

4

You only need to add the new keyword so that it creates a new object:

printArray(reverseArray(new int[] {1,2,3,4,5}));

If you define your reverseArray method to take int... instead of int[], then you can also use the following, which I'd argue is more readable:

printArray(reverseArray(1, 2, 3, 4, 5));
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • Is there also any efficiency difference in using int... and letting the compiler handle the array creation or is that purely syntactic sugar? – A.D Jan 09 '19 at 16:50
  • I’m pretty sure it’s just sugar, but even if it provided *some* efficiency benefit, I’d prefer it regardless because of the readability improvement. – Jacob G. Jan 09 '19 at 16:52
0

Just add the new keyword as below,

printArray(reverseArray(new int[] {1,2,3,4,5}));
Sandeepa
  • 3,457
  • 5
  • 25
  • 41