Here is a very very important question frequently asked in IT companies
=================================
Question: What is the var args method in java. Explain by using code.
Answer: A method that can be invoked by passing variable number of arguments is known as var args methods (or variable length arguments method). This concept was introduced in JDK1.5.
Example =>
class Foo
{
/*
Three dots (...) are known as elipses.
This method is a var args method, so we can pass any number
of arguments inside this method.
*/
void aMethod(String...args)
{
// show the values of array using for-each loop
for(String s : args)
{
System.out.println(s);
}
System.out.println("-----------------------------");
}
/*
explanation :
when we call var args method, the JVM (Java Virtual Machine) creates
an array to store the values of arguments, the size of this array will be
equal to the no of arguments passed
*/
public static void main(String[] args)
{
// create object of class Foo
Foo f = new Foo();
// call the var args method
// here i am passing no arguments
// so jvm will create array of size 0
System.out.println("data of array when zero argument is passed=>");
f.aMethod();
// here i am passing 2 string type arguments
// so jvm will create array of size 2
System.out.println("data of array when 2 argument are passed=>");
f.aMethod("apple","banana");
// here i am passing 4 string type arguments
// so jvm will create array of size 4
System.out.println("data of array when 4 arguments are passed=>");
f.aMethod("apple","banana","cherry","dates");
}
}
=================================
output of this program
==================================
data of array when zero argument is passed=>
-----------------------------
data of array when 2 argument are passed=>
apple
banana
-----------------------------
data of array when 4 arguments are passed=>
apple
banana
cherry
dates
-----------------------------
Thanx sir
ReplyDeleteThanks for sharing this good blog.It's amazing blogJava Online Training
ReplyDelete