You Don't Know Java #EP2 Java Var-args Method

You Don't Know Java #EP2
Java Var-args Method

GUESS THE ANSWER FIRST

class Demo{
    public static void main(String ... args){
        System.out.println("WOW");
    }
}
  1. WOW
  2. Compile Time Error
  3. Runtime Error
  4. No error

Answer: WOW

If you did it right No problem. If you did it wrong Let's fix that.

Your first question would be what is that ugly ... operator? Well, that operator is used in var arg method so now what are var-args method and why do we need it? First Learn about the non var-args method

Example: Non var arg method

class NonVarArg {

    public int add(int a, int b){
        return a+b;
    }

    public int add(int a, int b, int c){
        return a+b+c;
    }

    public static void main( String[] args ) {
        NonVarArg obj = new NonVarArg();
        System.out.println(obj.add(10, 20));
        System.out.println(obj.add(10, 20, 30));
    }
}
//add(10,20) -> 30
//add(10,20,30) -> 60

I don't need to tell you about what's happening in this code but what if I want to call add(10,20,30,40) compiler will error there is not such method. That's why we need var-arg methods.

Problem in non-arg:call add(10,20,30,40) I can't call this method which is my need.

Now look at Var-arg and how did java 1.5 version resolve it

Example: var arg method

class VarArg {
   public int add(int ... a){
        int sum=0;
        for(int i:a){
            sum+=i;
        }
        return sum;
    }
    public static void main( String[] args ) {
        VarArg obj = new VarArg();
        System.out.println(obj.add(10, 20));
        System.out.println(obj.add(10, 20, 30));
        System.out.println(obj.add(10, 20, 30,40));
    }
}
//add(10,20) -> 30
//add(10,20,30) -> 60
//add(10,20,30,40)->100

So now you can pass N number of arguments in that method

I hope you understand what is var-arg method. You can use it when you don't know how many number of arguments you are going to use. Then you can go for var-arg method.

HOW DOES IT WORKS?

Your eyes -> add(int ... a)

Compiler eyes -> add(int [] a)

MAIN METHOD EXAMPLE:

Your eyes -> public static void main(String ... args)

Compiler eyes -> public static void main(String [] args)

Did you find this article valuable?

Support Hritik manbattulwar by becoming a sponsor. Any amount is appreciated!