Câu hỏi phỏng vấn Java
Câu hỏi

What do the ... dots in the method parameters mean in java?

Câu trả lời

In Java, the three dots (...) used in method parameters are known as varargs, which stands for variable arguments. This feature allows a method to accept zero or more arguments of a specified type. Varargs can be very useful when you do not know in advance how many arguments will be passed to the method, or if you want the method to handle an arbitrary number of arguments.

Understanding Varargs

When you declare a method with a varargs parameter, you are telling the Java compiler that this method can accept an array of arguments of the specified type. The varargs parameter is always the last parameter in the method's signature. Here's how you can define and use a varargs method:

java Copy
public void printNumbers(int... numbers) {
    for (int number : numbers) {
        System.out.println(number);
    }
}

In this example, printNumbers can be called with any number of int arguments, or even no arguments at all:

java Copy
printNumbers(1, 2, 3);  // prints 1, 2, 3
printNumbers(4, 5, 6, 7);  // prints 4, 5, 6, 7
printNumbers();  // prints nothing

Important Rules and Considerations

  1. Single Varargs Parameter: A method can have only one varargs parameter.
  2. Position: The varargs parameter must be the last parameter in the method's signature.
  3. Syntax: The varargs syntax is simple: it uses three dots (...) followed by the parameter type and the parameter name.

Examples and Usage

Varargs are particularly useful when you need a method to handle a variable number of parameters without overloa...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Why is Spring MVC better than Servlets / JSP ?

middle

What’s a deadlock?

senior

What is the main difference between an inner class and a static nested class in Java?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào