Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between byte[] and byte ... in Java Methods

Someone asked me what the difference between the two method parameters and why you would use the ... over specifically assigned array.

putMessage(byte ...send)

putMessage(byte[] send)

I couldn't answer them with confidence and couldn't remember what the ... is called.

like image 284
JPM Avatar asked Dec 27 '22 13:12

JPM


1 Answers

The ... in your first example are called varargs. Your second example has an array argument. Varargs are a convenience for times when you want to hard code a variable number of arguments to a method but don't want to manually create an array to hold them. It's a shorthand notation. Consider this:

putMessage(0b00100101, 0b00100101, 0b00100101); // varargs

vs. this:

putMessage(new byte[] { 0b00100101, 0b00100101, 0b00100101 }); // array

The first example is less cluttered and more readable.

like image 91
Asaph Avatar answered Jan 13 '23 13:01

Asaph