Showing posts with label varargs. Show all posts
Showing posts with label varargs. Show all posts

Monday, 25 July 2022

Constructors with variable number of arguments

In java we can create methods, constructors that takes variable number of arguments. This feature is called varargs or variable number of arguments.

 

Example

public class AirthmeticUtil {

    final int[] args;

    public AirthmeticUtil(int... args) {
        this.args = args;
    }
    .......
    .......
}

 


"..." tells the compiler that this is a vararg, and you can pass zero or more arguments to the AirthmeticUtil constructor.

 

AirthmeticUtil util1 = new AirthmeticUtil();
AirthmeticUtil util2 = new AirthmeticUtil(2);
AirthmeticUtil util3 = new AirthmeticUtil(2, 3);
AirthmeticUtil util4 = new AirthmeticUtil(2, 3, 5);

 

Find the below working application.

 

AirthmeticUtil.java

package com.sample.app.util;

public class AirthmeticUtil {

    final int[] args;

    public AirthmeticUtil(int... args) {

        this.args = args;

    }

    public Long sum() {

        if (this.args == null || this.args.length == 0) {
            return null;
        }

        long sum = 0;

        for (int i : args) {
            sum += i;
        }

        return sum;
    }

    public Long mul() {

        if (this.args == null || this.args.length == 0) {
            return null;
        }

        long result = 1;

        for (int i : args) {
            result *= i;
        }

        return result;
    }

}

 

App.java

package com.sample.app;

import com.sample.app.util.AirthmeticUtil;

public class App {

    public static void main(String[] args) {
        AirthmeticUtil util1 = new AirthmeticUtil();
        AirthmeticUtil util2 = new AirthmeticUtil(2);
        AirthmeticUtil util3 = new AirthmeticUtil(2, 3);
        AirthmeticUtil util4 = new AirthmeticUtil(2, 3, 5);

        System.out.println("Sum of numbers : " + util1.sum());
        System.out.println("Multiplication of numbers : " + util1.mul());

        System.out.println("\nSum of numbers : " + util2.sum());
        System.out.println("Multiplication of numbers : " + util2.mul());

        System.out.println("\nSum of numbers : " + util3.sum());
        System.out.println("Multiplication of numbers : " + util3.mul());

        System.out.println("\nSum of numbers : " + util4.sum());
        System.out.println("Multiplication of numbers : " + util4.mul());

    }
}

Output

Sum of numbers : null
Multiplication of numbers : null

Sum of numbers : 2
Multiplication of numbers : 2

Sum of numbers : 5
Multiplication of numbers : 6

Sum of numbers : 10
Multiplication of numbers : 30



 

 

  

Previous                                                 Next                                                 Home

Wednesday, 1 April 2020

Pass ArrayList to a method with varargs?

In java, you can create a method that takes variable number of arguments. This feature is called varargs or variable number of arguments. Method which accepts variable number of arguments is called varargs method.

Syntax
returnType methodName(dataType … parameterName){

}

"..." tells the compiler that this is a vararg.

For example, ‘printInfo’ method takes varargs of string as argument and prints.

private static void printInfo(String... data) {
    for (String str : data) {
        System.out.println(str);
    }
}

Since printInfo takes an array as argument, you can convert the list to an array and call this method like below.
printInfo(countries.toArray(new String[countries.size()]));

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class App {

    private static void printInfo(String... data) {
        for (String str : data) {
            System.out.println(str);
        }
    }

    public static void main(String args[]) {
        List<String> countries = Arrays.asList("India", "Sri Lanka", "Singapore", "Australia");

        printInfo(countries.toArray(new String[countries.size()]));
    }

}

Output
India
Sri Lanka
Singapore
Australia


You may like

Saturday, 22 December 2018

JavaScript: Explain spread operator

Spread operator represented by 3 dots (…) used to perform below things.
a.   It can turn elements of an array into arguments of a function call.
b.   Convert string to an array
c.   Convert set to an array
d.   Provide better way to concatenate arrays
e.   Copy elements of array to new array
f.    Merge object literals

Turn elements of an array into arguments of a function call
HelloWorld.js
function sum(...ele){
  var sum = 0;
  
  for(data of ele){
    sum += data;
  }
  
  return sum;
}

var result1 = sum(10);
var result2 = sum(10, 20);
var result3 = sum(10, 20, 30);

var arr = [10, 20, 30, 40];
var result4 =sum(...arr); //Expand the array into 4 arguments

console.log("result1 : " + result1);
console.log("result2 : " + result2);
console.log("result3 : " + result3);
console.log("result4 : " + result4);

Output
result1 : 10
result2 : 30
result3 : 60
result4 : 100

Convert string to an array
HelloWorld.js
var str = "Hello World";
var chars = [...str];

console.log(chars)

Output
Array(11) [ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", … ]

Convert set to an array
Example
var arr = [...countries];

HelloWorld.js
var countries =  new Set();

countries.add("India");
countries.add("Australia");
countries.add("Canada");
countries.add("Germany");

var arr = [...countries];

console.log(arr);


Output
Array(4) [ "India", "Australia", "Canada", "Germany" ]

Provide better way to concatenate arrays
If you want to concatenate elements of two arrays, you may have to write below kind of code.

function concatenateArray(arr1, arr2){
  var result = [];
 
  for(var ele of arr1){
    result.push(ele);
  }
 
  for(var ele of arr2){
    result.push(ele);
  }
 
  return result;
}

HelloWorld.js
var asiaCountries = ["Japan", "India", "Indonesia", "Singapore"];
var europeCountries = ["Germany", "France", "Italy"];

function concatenateArray(arr1, arr2){
  var result = [];
  
  for(var ele of arr1){
    result.push(ele);
  }
  
  for(var ele of arr2){
    result.push(ele);
  }
  
  return result;
}

var asiaAndEuropeCountries = concatenateArray(asiaCountries, europeCountries);


console.log(asiaCountries);
console.log(europeCountries);
console.log(asiaAndEuropeCountries);


Output
Array(4) [ "Japan", "India", "Indonesia", "Singapore" ]
Array(3) [ "Germany", "France", "Italy" ]
Array(7) [ "Japan", "India", "Indonesia", "Singapore", "Germany", "France", "Italy" ]

With spread operator, you can concatenate using below statement.

var asiaAndEuropeCountries = [...asiaCountries, ...europeCountries];

HelloWorld.js
var asiaCountries = ["Japan", "India", "Indonesia", "Singapore"];
var europeCountries = ["Germany", "France", "Italy"];

var asiaAndEuropeCountries = [...asiaCountries, ...europeCountries];

console.log(asiaCountries);
console.log(europeCountries);
console.log(asiaAndEuropeCountries);

Output
Array(4) [ "Japan", "India", "Indonesia", "Singapore" ]
Array(3) [ "Germany", "France", "Italy" ]
Array(7) [ "Japan", "India", "Indonesia", "Singapore", "Germany", "France", "Italy" ]

Copy elements of array to new array
var asiaCountries = ["Japan", "India", "Indonesia", "Singapore"];
var copiedData = [...asiaCountries];

HelloWorld.js
var asiaCountries = ["Japan", "India", "Indonesia", "Singapore"];
var copiedData = [...asiaCountries];

console.log(asiaCountries);
console.log(copiedData);


Output
Array(4) [ "Japan", "India", "Indonesia", "Singapore" ]
Array(4) [ "Japan", "India", "Indonesia", "Singapore" ]

Merge Object literals
HelloWorld.js
var obj1 = { foo: 'bar', x: 52 };
var obj2 = { foo: 'baz', y: 103 };
var obj3 = { foo: 'baz', x : 100, z : 1000 };

var mergedObject = { ...obj1, ...obj2, ...obj3 };

console.log(mergedObject);

Output
Object { foo: "baz", x: 100, y: 103, z: 1000 }


Previous                                                 Next                                                 Home

Friday, 14 December 2018

JavaScript: Rest Parameter

Rest parameters are used to represent variable number of arguments. It is equivalent to Varargs in Java. ‘…’ are used to represent variable number of arguments.

HelloWorld.js
function sum(...arr){
    var sum = 0;
    
    for(data of arr){
        sum += data;
    }
    
    return sum;
}

var x = sum(10, 20);
var y = sum(10, 20, 30, 40);

console.log("x : " + x);
console.log("y : " + y);

Output
x : 30
y : 100


Previous                                                 Next                                                 Home

Saturday, 8 February 2014

Overloading varargs

 Just like normal methods, java provides facility to overload vararg methods also.

Example
class VaragOverload{

 void print(int ... a){ 
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }

 void print(boolean ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }

 public static void main(String args[]){
  VaragOverload obj = new VaragOverload();
  obj.print(1,2,3);
  obj.print(true, false, true);
 }
}

Output    
1
2
3
true
false
true 
      
Ambiguity while using varargs
Consider the above example, there is a problem in that. Try to call the method “print” with no arguments, then compiler throws the error, since it can't differentiate which overloaded method, it should call.

Example      
class VaragOverload{
 void print(int ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }
  
 void print(boolean ... a){
  for(int i=0; i < a.length; i++){
   System.out.println(a[i]);
  }
 }
  
 public static void main(String args[]){
  VaragOverload obj = new VaragOverload();
      
  obj.print(1,2,3);
  obj.print(true, false, true);
  obj.print();
 }       
}
      
When you try to compile, compiler throws the below error
VaragOverload.java:20: error: reference to print is ambiguous, both method print(int...) 
in VaragOverload and method print(boolean...) in VaragOverload match     
    obj.print();
       ^
    1 error  



Overloading Methods                                                 Constructors                                                 Home

Varargs: Methods with variable number of arguments

In java we can create methods that takes variable number of arguments. This feature is called varargs or variable number of arguments. The method which accepts variable number of arguments is called varargs method.
Syntax
    returnType methodName(dataType … parameterName){

    }

"..." tells the compiler that this is a vararg.

Example
class VarargsEx{
 public void printData(int ... a){
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++)
   System.out.print(a[i] + " ");
  System.out.println();
 }

 public static void main(String args[]){
  VarargsEx obj = new VarargsEx();
  obj.printData(1);
  obj.printData(1,2);
  obj.printData(1,2,3);
 }
}

Output
Parameters are 1
1
Parameters are 2
1 2
Parameters are 3
1 2 3

The syntax for the method printData, tells the compiler, that this method can accept zero or more arguments. So all the calls like below are valid.
      obj.printData(1);
    obj.printData(1,2);
    obj.printData(1,2,3);

The variable number of parameters (varargs) must be at last while defining a method with varargs.

There must be only one vararg parameter in method definition.

Some Points to Remember
1. The variable number of parameters (varargs) must be at last while defining a method with varargs.
    Example
class VarargsEx{
 public void printData(int ... a, float f1){ 
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++) 
   System.out.print(a[i] + " ");
  System.out.println();
 } 
} 
           
When you try to compile the above program, compiler will generates error like below

VarargsEx.java:3: error: ')' expected
public void printData(int ... a, float f1){
 ^
VarargsEx.java:3: error: ';' expected
public void printData(int ... a, float f1){
 ^
2 errors
               

valid method definition is
    public void printData(float f1, int ... a)

2. There must be only one vararg parameter in method definition.
      Example
class VarargsEx{
 public void printData(int ... a1, int ... a2){
 }
}
     
When you try to compile the above code, compiler throws error like below             
VarargsEx.java:3: error: ')' expected
public void printData(int ... a1, int ... a2){
 ^

VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
 ^
 
VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
^
3 errors

More about methods                                                 constructore varargs                                                 Home