Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Return multiple values in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 915
    Comment on it

    Java doesn’t support multi-value returns but if all returned elements are of same type then an array can be returned which in turn is returning multiple values.

    // A Java program to demonstrate that a method
    // can return multiple values of same type by
    // returning an array
    class Demo
    {
    	// Returns an array such that first element
    	// of array is a+b, and second element is a-b
    	static int[] getSumAndSub(int a, int b)
    	{
    		int[] resultarr = new int[2];
    		resultarr[0] = a + b;
    		resultarr[1] = a - b;
    
    		// returning array of elements
    		return resultarr;
    	}
    	public static void main(String[] args)
    	{
    		int[] resultarr = getSumAndSub(100,50);
    		System.out.println("Sum of passed numbers = " + resultarr[0]);
    		System.out.println("Subtraction of passed numbers = " + resultarr[1]);
    	}
    }

     

    Output:

    Sum of passed numbers = 150
    Subtraction of passed numbers = 50

     

    Explanation:

    In above program from main, two variables a and b are passed to function getSumAndSub, the function which is evaluating addition and subtraction of passed numbers. The addition and subtraction of passed numbers can be returned by keeping them in an array and returning the array from function thus returning multiple values.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: