Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper terminology for Object... args

Tags:

java

methods

args

I'm working in Java and the typical way you specify multiple args for a method is:

public static void someMethod(String[] args)

But, I've seen another way a few times, even in the standard Java library. I don't know how to refer to this in conversation, and googling is not of much help due to the characters being used.

public static void someMethod(Object... args)

I know this allows you to string a bunch or arguments into a method without knowing ahead of time exactly how many there might be, such as:

someMethod(String arg1, String arg2, String arg3, ... etc

How do you refer to this type of method signature setup? I think it's great and convenient and want to explain it to some others, but am at a lack of how to refer to this. Thank you.

like image 201
SnakeDoc Avatar asked May 21 '13 15:05

SnakeDoc


People also ask

What is the meaning of args?

Usually, ... args means "any number of values". For example, you could pass null or 1,2,3,4 - it would not matter and the method is smart enough to deal with it.

When an object is passed as an argument to a method?

When passing an argument by reference, the method gets a reference to the object. A reference to an object is the address of the object in memory. Now, the local variable within the method is referring to the same memory location as the variable within the caller.

What are variable arguments or Varargs?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }

What are method parameters in Java?

Parameters and Arguments Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.


2 Answers

This way to express arguments is called varargs, and was introduced in Java 5.
You can read more about them here.

like image 158
Keppil Avatar answered Nov 03 '22 11:11

Keppil


As a Keppil and Steve Benett pointed out that this java feature is called varargs.

If I'm not mistaken, Joshua Bloch mentioned that there is a performance hit for using varargs and recommends telescoping and using the varargs method as a catch all sink.

public static void someMethod(Object arg) {
    // Do something
}

public static void someMethod(Object arg1, Object arg2) {
    // Do something
}

public static void someMethod(Object arg1, Object arg2, Object arg3) {
    // Do something
}

public static void someMethod(Object ... args) {
    // Do something
}
like image 39
Dan Avatar answered Nov 03 '22 12:11

Dan