How to write a function which can return two integers?

How to write a function which can return two integers?




There is no such default way that a function can return multiple values. But there are some user-defined ways through that we can create a function that returns multiple values.

The first way to achieve this is by using the constructor. The example has given below


public class integer {
    private int a;
    private int b;

    integer() {

    }

    integer(int a, int b) {
        this.a = a;
        this.b = b;
    }

    integer sum(int c, int d) {
        integer result = new integer(c, d);
        return result;
    }

    public static void main(String[] args) {
        integer i = new integer();
        integer n = i.sum(10, 12);
        System.out.println(n.a);
        System.out.println(n.b);
    }

}
Another way is to use an array. the example has given below

public class integer {

    int[] sum(int c, int d) {
        int arr[] = new int[2];
        arr[0]=c;
        arr[1]=d;
        return arr;
    }

    public static void main(String[] args) {
        integer i =new integer();
        int[] n = i.sum(70, 50);
        System.out.println(n[0]);
        System.out.println(n[1]);
    }

}

Post a Comment

0 Comments