Home Java javaTutorial Variadic functions in Java

Variadic functions in Java

Nov 20, 2024 am 01:00 AM

Funciones variádicas en Java

A variadic function is one that accepts an indefinite number of parameters.

Let's see what the reason for these functions is within Java. Suppose we have a summation method that receives two integers and returns the sum of both.

public static int summation(int a, int b) {
    return a + b;
}
Copy after login
Copy after login

If we want to add three numbers, we would have to overload the summation method to accept three parameters.

public static int summation(int a, int b, int c) {
    return a + b + c;
}
Copy after login
Copy after login

What happens if we want to add four numbers? Again the summation method must be overloaded.

public static int summation(int a, int b, int c, int d) {
    return a + b + c + d;
}
Copy after login
Copy after login

As we can see this is not scalable, since each time a different number of parameters is needed, the method would have to be overloaded again. At this point you could consider passing an array of integers as a parameter, but this does nothing more than wrap the actual parameters and make the method now depend on a new data type explicitly.

For these cases, variadic functions exist, to accept an indefinite number of parameters without the need to wrap them in another type of visible structure. It is important to consider that internally what Java does is create an array with the parameters that are passed to the variadic function, so we can work with methods of an array.

A variadic function is declared in the same way as any normal function, but as parameters the last or only parameter it has will have to comply with the following format: datatype... variablename. Within the way it is declared the only thing that changes is the addition of the three dots... after the data type. In some languages ​​this type of parameter is known as varargs. Let's see how the summation method looks like a variadic function.

public static int summation(int... numbers) {
    int sum = 0;

    for (int number : numbers) {
        sum += number;
    }

    return sum;
}
Copy after login

Now we can add any number of numbers without the need to overload the summation method, with the only restriction that they must all be of the same data type.

System.out.println(summation(1, 2)); // 3
System.out.println(summation(1, 2, 3)); // 6
System.out.println(summation(1, 2, 3, 4)); // 10
System.out.println(summation(2, 8, 16, 32, 64, 128, 256, 512, 1024, 2048)); // 4090
Copy after login

Before it was mentioned that internally Java handles the parameters of a variadic function as an array, that is, it wraps them within an array, and this allows us to work with methods of an array. For example, you can use the sum method of the Arrays class to add all the elements of the array within the summation method.

public static int summation(int... numbers) {
    return Arrays.stream(numbers).sum();
}
Copy after login

Considering the above, a variadic function can also be passed as a parameter an array of the type of data it accepts, no matter how curious it may seem. In this way Java no longer has to wrap the parameters in an array, since an array is being passed directly as an argument.

public static int summation(int a, int b) {
    return a + b;
}
Copy after login
Copy after login

But what happens if the summation method for some reason needs a second parameter of type double, in addition to the n integers that it can already receive when declared as a variadic function. In this case, the summation method would have to be declared with the additional parameters it needs and at the end the variadic parameter or varargs, as shown below.

public static int summation(int a, int b, int c) {
    return a + b + c;
}
Copy after login
Copy after login

In this way you can pass a double number as the first parameter and the integers that you want to add as additional parameters and Java will automatically know that the first parameter is of type double and the following are of type int, consider that the parameter variadic should always be the last parameter of the function, and not the first, since it would generate a compilation error, even the IDE itself would tell us the following: varargs parameter must be the last parameter.

public static int summation(int a, int b, int c, int d) {
    return a + b + c + d;
}
Copy after login
Copy after login

In conclusion, if some utility function is required to perform some type of operations with an indefinite number of parameters and we do not want to pass an array or a list explicitly, the use of a variadic function can be considered. These are useful, they allow the code to be cleaner and more scalable, and they avoid method overloading.

The above is the detailed content of Variadic functions in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles