I'm a beginner in Java, and while I was exploring I got to see a code which has the usage as Fruit... fruitName
? I have ever seen such a usage in any documentation like ...
Can anyone know what and how the usage of this?
I'm a beginner in Java, and while I was exploring I got to see a code which has the usage as Fruit... fruitName
? I have ever seen such a usage in any documentation like ...
Can anyone know what and how the usage of this?
No, a class name in Java cannot contain the .
character.
The ...
syntax is a way of declaring a method that receives any number of arguments from a given type (and treats them internally as an array.
E.g.:
public void printAllFruits (Fruit... fruits) {
// fruits is a Fruit[]:
for (Fruit fruit : fruits) {
System.out.println(fruit);
}
}
public static void main(String[] args) {
Fruit f1 = new Fruit("apple");
Fruit f2 = new Fruit("pear");
Fruit f3 = new Fruit("banana");
// This would work:
printAllFruits(f1);
// And so will this:
printAllFruits(f1, f2, f3);
}
valid characters in a java class name
... is used in Java also. It's called variable argument. It is used when you want to get some arguments which have same type, but the number of arguments is not sure. It's also used in C. Think about scanf/printf function.
class Fruit {
// Class implementation
}
public void extractJuice(Fruit... args) {
// This method can take variable arguments of type Fruit
}
So what you are looking at is varargs short for Variable Arguments.
Futher references: - When do you use varargs in Java?
The only things you can have in a class name in Java are alphabetical letters of any case, numbers (although you can't start a class name with a number) and underscores.
The only case that an ellipsis (...
) can follow a class name is when you're specifying a variable argument list of that class.
Consider the function foo
, defined
void foo(Fruit... fruits){
for (fruit : fruits){
/*each argument considered here*/
}
}
foo
could then be called with any number of Fruit
instances.