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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 8.72k
    Comment on it
    // A Java program to demonstrate that we can return multiple values of different types by making a class
    // and returning an object of class.
    
    // A class that stores and returns two members of different types
    class Test
    {
    	int mul; // To store multiplication
    	double div; // To store division
    	Test(int m, double d)
    	{
    		mul = m;
    		div = d;
    	}
    }
    
    class Demo
    {
    	static Test getMultandDiv(int a, int b)
    	{
    		// Returning multiple values of different
    		// types by returning an object
    		return new Test(a*b, (double)a/b);
    	}
    
    	// Driver code
    	public static void main(String[] args)
    	{
    		Test result = getMultandDiv(30, 9);
    		System.out.println("Multiplication = " + result.mul);
    		System.out.println("Division = " + result.div);
    	}
    }

    Output:

    Multiplication = 270
    Division = 3.3333333333333335

    Explanation:

    Java doesn’t support multi-value returns but returning multiple values with different datatype in Java is possible via creating a class. In above case Test and encapsulating encapsulating all returned types into that class in above case a double and an integer value is to be returned. Finally an object of Test class can be returned i.e in Demo class a static function getMultandDiv which returns an object of Test class is created and two parameters are passed to it. This function is then called from main passing a double and an integer value to it,these value are manipulated accordingly and returned by encapsulating them in Test object. 
     

     

 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: