0

Is it possible to pass multiple numbers as a parameter for an array parameter? Just like I would with a regular int. Or does the parameter have to be a separate array that I have to create?

public static void main(String[] args) {

getIntegers(1,2,3,4,5);

}

public static void getIntegers(int[] array) {

//write whatever here

}
2
  • Hey Aomine-Sorry if this is a duplicate but I looked at that question and it just seemed to confuse me more, as I didn't understand what was being asked. Commented May 25, 2017 at 15:16
  • here is a better duplicate --> Java method with unlimited arguments. There are many answers to this question and a quick google search would provide a lot of useful answers. Commented May 25, 2017 at 15:19

1 Answer 1

3

You can use varargs.

public static void getIntegers(int... array)

It can be referenced as an int[] from within the method body.

The method can be invoked by passing any given number of ints, or null.

Also note

  • You cannot declare more than one varargs per method signature.
  • If you intend to declare more than one parameter in your method, the varargs must be the last one
Sign up to request clarification or add additional context in comments.

1 Comment

Hey Mena! Thanks for your answer, I have not gotten to the varargs chapter yet, so when I saw the "..." i thought it meant "type info here" and wasn't an actual command.

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.