- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java Varargs (Variable Length Arguments)
Beginning with JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called as varargs (short for variable-length arguments).
A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method.
Situations that require a variable number of arguments be passed to a method are not unusual. For example, a method that opens an Internet connection might take a user name, password, filename, protocol, and so on, but supply defaults if some of this information is not provided. In this situation, it would be convenient to pass only the arguments to which the defaults did not apply. Another example is printf() method that is a part of Java's I/O library, it takes a variable number of arguments, which it formats and then outputs.
Prior to JDK 5, variable-length arguments could be handled in two ways, neither of which was particularly pleasing. First, if the maximum number of arguments was small and known, then you could create overloaded versions of the method, one for each way the method could be called. Although this works and is suitable for some cases, it applies to only a narrow class of situations.
In cases where the maximum number of potential arguments was larger, or unknowable, a second approach was used in which, arguments were put into an array, and then the array was passed to the method. This approach is illustrated by the following program :
Java Varargs Example
Here is an example demonstrating varargs in Java:
/* Java Program Example - Java Varargs (Variable-Length) Arguments * Use an array to pass a variable number of arguments * to a method. This is the old-style approach to variable-length * arguments. */ class JavaProgram { static void vaTest(int v[]) { System.out.print("Number of arguments = " + v.length + ", Contents = "); for(int x : v) { System.out.print(x + " "); } System.out.println(); } public static void main(String args[]) { /* notice how an array must be create to * hold the arguments */ int n1[] = { 10 }; int n2[] = { 1, 2, 3 }; int n3[] = { }; vaTest(n1); // 1 argument vaTest(n2); // 3 arguments vaTest(n3); // no arguments } }
When the above Java program is compile and executed, it will produce the following output:
In the above program, the method vaTest() is passed its argument through the array v. This old-style approach to the variable-length arguments does enable the vaTest() to take an arbitrary number of arguments. However, it requires that these arguments be manually packaged into an array prior to calling the vaTest(). Not only is it tedious to construct an array each time the vaTest() is called, it is potentially error-prone. The varargs feature offers a simpler, better option.
A variable-length argument is specified by three periods (...). For example, here is how the vaTest() is written using a vararg:
static void vaTest(int ... v) {
This syntax tells the compiler that the vaTest() can be called with zero or more arguments. As a result, v is implicitly declared as an array of type int[]. Thus, inside the vaTest(), v is accessed using the normal array syntax. Here is the preceding program rewritten using a vararg:
/* Java Program Example - Java Varargs (Variable-Length) Arguments * This program demonstrate variable-length arguments */ class JavaProgram { /* vaTest() now uses a vararg */ static void vaTest(int ... v) { System.out.print("Number of arguments = " + v.length + ", Contents = "); for(int x : v) { System.out.print(x + " "); } System.out.println(); } public static void main(String args[]) { /* notice how vaTest() can be called with * a variable number of arguments */ vaTest(10); // 1 argument vaTest(1, 2, 3); // 3 arguments vaTest(); // no arguments } }
When the above Java program is compile and executed, it will produce the following output (same as previous one):
There are two important things to notice about this program. First, as explained, inside the vaTest(), v is operated on as an array. This is because v is an array. The ... syntax tells the compiler that a variable number of arguments will be used, and that these arguments will be stored in the array referred to by v. Second, in the main(), the vaTest() is called with different numbers of arguments, including no arguments at all. The arguments are automatically put in an array and passed to v. In the case of no arguments, the length of the array is zero.
A method can have "normal" parameters along with a variable-length parameter. However, the variable-length parameter must be the last parameter declared by the method. For example, this method declaration is perfectly acceptable:
int doIt(int a, int b, double c, int ... vals) {
In this case, the first three arguments used in a call to doIt() are matched to the first three parameters. Then, any remaining arguments are assumed to belong to vals.
Remember, the varargs parameter must be last. For example, the following declaration is incorrect :
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
Here, there is an attempt to declare a regular parameter after the varargs parameter, which is illegal.
There is one more restriction to be aware of, there must be only one varargs parameter.
Following is a reworked version of the vaTest() method that takes a regular argument and a variable-length argument :
/* Java Program Example - Java Varargs (Variable-Length) Arguments * This program uses varargs with standard arguments */ class JavaProgram { /* here, msg is a normal parameter and v is a * varargs parameter */ static void vaTest(String msg, int ... v) { System.out.print(msg + v.length + ", Contents = "); for(int x : v) { System.out.print(x + " "); } System.out.println(); } public static void main(String args[]) { vaTest("One vararg : ", 10); vaTest("Three varargs : ", 1, 2, 3); vaTest("No varargs : "); } }
When the above Java program is compile and executed, it will produce the following output:
« Previous Tutorial Next Tutorial »