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

?

0

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Is there also any efficiency difference in using int... and letting the compiler handle the array creation or is that purely syntactic sugar?
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.
0

Just add the new keyword as below,

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.