Returning Multiple Values in JavaJava does not support multiple return values. However, sometimes it is required to return multiple values. For that, we can use the following solutions. Case 1: If all of the returned values are the sameIf all the values that have to be returned are the same, then we can use an array. For example, two numbers are given, and it is required to perform the addition, subtraction, multiplication and division on these numbers. In such a scenario, we can use an array. Observe the following program. FileName: ReturnMultipleValues.java Output: The sum of numbers 6 and 3 is: 9 The difference of numbers 6 and 3 is: 3 The multiplication of numbers 6 and 3 is: 18 The division of numbers 6 and 3 is: 2 Complexity Analysis: Since the program is using a for-loop for computing the sum of elements, the time complexity of the program is O(n), where n is the total number of elements present in the array. The space complexity of the program is constant, i.e., O(1). Case 2: If we have to return two values of different typesIn case we have the two values of the different types, we can use Pair. FileName: ReturnMultipleValues1.java Output: JavaTpoint 100 Case 3: If we have to return more values of different typesIn that case, we can use a class. Observe the following program. FileName: ArithmeticOperation.java Output: Statement: Performing Arithmetic Operation The Multiplication of the numbers 29 and 20 is: 580 The Division of the numbers 29 and 20 is: 1.45 The Addition of the numbers 29 and 20 is: 49 Next TopicCentered Square Numbers in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India