Hackforge Academy

Category: java

Vararg method

Published on 22 Feb 2026

Explanation


Varargs allow a method to accept a
variable number of arguments.

Code:

void display(int... numbers) {
    for(int n : numbers) {
        System.out.println(n);
    }
}

Explanation


Varargs are treated as arrays inside the method.

Code:

void sum(int... values) {
    System.out.println(values.length);
}

Explanation


Varargs parameter must be the last
parameter in the method.

Code:

void example(String name, int... marks) { }

Explanation


You can call varargs method with zero or
more arguments.

Code:

display();
display(1, 2, 3);

Explanation


Only one varargs parameter is allowed in a
method.

Code:

// void test(int... a, int... b) {} // Not allowed

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community