Java

How to return 2 values from a Java method

27 September 2026 · 10 min read

How to return 2 values from a Java method

In Java, a method is traditionally designed to return a single value. However, there are scenarios where you need to return multiple pieces of information from a method. This can be a common requirement in complex algorithms, data processing, or when performing operations that naturally yield several results. Understanding how to effectively return 2 values from a Java method is crucial for writing clean, efficient, and maintainable code. Several approaches can accomplish this, each with its own advantages and disadvantages. This article explores these different techniques, providing practical examples and guiding you on when to use each method to enhance your Java programming skills. Choosing the right approach ensures your code remains readable and performs optimally.

Using Arrays to Return Multiple Values

One straightforward method to return 2 values from a Java method is by using arrays. Since arrays can hold multiple elements of the same data type, you can package the values you want to return into an array and return the array. This is particularly useful when the values you’re returning are of the same type. For example, if you’re writing a method to find the minimum and maximum values in a list of integers, you can return an integer array of size two, with the first element being the minimum and the second being the maximum.

However, using arrays directly can make the code less readable if you don’t clearly document what each index represents. Without proper documentation, other developers (or even you, after some time) might struggle to understand the purpose of each returned value. It’s important to make sure you clearly indicate what each index in the array represents. For instance, you could add comments to your code or choose descriptive variable names to make it easier to understand. “While using arrays might seem simple initially, it’s crucial to consider the long-term maintainability and readability of your code,” according to a study on code maintainability from the Software Engineering Institute at Carnegie Mellon University SEI.

Here’s a simple example demonstrating how to return an array containing two values:

java public class ArrayExample { public static int[] getMinMax(int[] numbers) { int min = numbers[0]; int max = numbers[0]; for (int number : numbers) { if (number < min) { min = number; } if (number > max) { max = number; } } return new int[]{min, max}; } public static void main(String[] args) { int[] numbers = {5, 2, 9, 1, 5, 6}; int[] result = getMinMax(numbers); System.out.println(“Min: " + result[0] + “, Max: " + result[1]); } } Leveraging Java Objects to Return Multiple Values

A more structured and readable approach to return 2 values from a Java method involves creating a custom Java object (a class) to encapsulate the values you want to return. This method offers better organization and clarity, especially when the values are of different data types or represent distinct entities. For example, you could create a class named Result that contains fields for an integer and a string. This way, when the method returns an instance of this Result class, it’s immediately clear what each value represents.

Using a custom class improves code readability and maintainability significantly. The class fields can have meaningful names, which clearly describe the purpose of each returned value. Additionally, you can add methods to this class to perform operations on the returned values, further enhancing its utility. However, this approach involves creating a new class, which may seem like more overhead for simple cases. Despite the added complexity, the benefits in terms of readability and maintainability often outweigh the extra effort, especially in larger projects. For instance, consider a method that needs to return a user’s ID and their registration date. Creating a UserRegistration class with userId and registrationDate fields would provide a much cleaner and more descriptive solution than using an array or other less structured methods.

Here’s an example of how to implement this:

java class Result { private int value1; private String value2; public Result(int value1, String value2) { this.value1 = value1; this.value2 = value2; } public int getValue1() { return value1; } public String getValue2() { return value2; } } public class ObjectExample { public static Result processData(String input) { int processedValue = input.length(); String message = “Processed: " + input; return new Result(processedValue, message); } public static void main(String[] args) { Result result = processData(“Example”); System.out.println(“Value 1: " + result.getValue1() + “, Value 2: " + result.getValue2()); } } Utilizing the Pair Class from Libraries

Several libraries, like Apache Commons Lang and Vavr, provide a Pair class that can be used to return 2 values from a Java method. This class is specifically designed to hold a pair of values, making it a convenient option when you don’t want to create a custom class for a simple pair. These classes are often generic, allowing you to specify the data types of the two values. Using a Pair class can reduce the amount of boilerplate code you need to write and can improve code readability by clearly indicating that you are returning a pair of related values.

Using existing libraries can save development time and ensure that your code is well-tested and reliable. However, it’s important to consider the dependencies you are adding to your project. Adding a library for a single feature might not be worth it if the library is large or if you only need the Pair class in one or two places. In such cases, creating a simple custom class might be a better option. According to a report by Sonatype, “Managing dependencies effectively is crucial for maintaining the health and security of your software projects” Sonatype.

Below is an example using the Pair class from Apache Commons Lang:

java import org.apache.commons.lang3.tuple.Pair; public class PairExample { public static Pair processData(String input) { int processedValue = input.length(); String message = “Processed: " + input; return Pair.of(processedValue, message); } public static void main(String[] args) { Pair result = processData(“Example”); System.out.println(“Value 1: " + result.getLeft() + “, Value 2: " + result.getRight()); } } Returning Values via Output Parameters

Another way to return 2 values from a Java method is by using output parameters. While Java doesn’t directly support output parameters like some other languages (e.g., C++ with pointers or C with out parameters), you can simulate this behavior by passing mutable objects as arguments to the method. The method can then modify these objects, effectively returning values through them. This approach is less common in modern Java development due to potential confusion and decreased readability, but it’s still a viable option in certain situations.

The key to using output parameters effectively is to clearly document that the passed objects are intended to be modified by the method. Without this clear indication, developers might be surprised to find that their objects have been changed after calling the method, leading to unexpected behavior and bugs. Using output parameters can make your code harder to reason about, as the state of the objects passed as arguments can change during the method execution. Therefore, it’s generally recommended to use this approach sparingly and only when other methods are not suitable. For example, if you need to update an existing object with multiple new values and returning a new object would be inefficient, output parameters might be a reasonable choice.

Here’s an example illustrating the use of a mutable object (StringBuilder) as an output parameter:

java public class OutputParameterExample { public static void processData(String input, StringBuilder message) { message.append(“Processed: “).append(input); } public static void main(String[] args) { StringBuilder message = new StringBuilder(); processData(“Example”, message); System.out.println(“Message: " + message.toString()); } } Choosing the Right Approach

Deciding how to return 2 values from a Java method depends largely on the specific context of your code. Each method offers a unique set of advantages and disadvantages. The best approach will depend on factors such as the number of values you need to return, their data types, and the overall readability and maintainability of your code.

Here are some guidelines to help you choose the best method:

  • Arrays: Use when returning multiple values of the same type and when performance is critical, but remember to document the meaning of each index.
  • Custom Objects: Ideal for returning values of different types and when readability and maintainability are paramount.
  • Pair Class: A convenient option when you need to return a pair of values and don’t want to create a custom class, but be mindful of adding unnecessary dependencies.
  • Output Parameters: Use sparingly, primarily when you need to update existing objects and other methods are not suitable, and always document clearly.

Consider these points when making your decision:

  • Code readability and maintainability
  • Performance requirements
  • The number and types of values you need to return
Infographic here illustrating the decision-making process for choosing the right return method.
FAQ Section -----------
**Q: Why can't I just return multiple values directly in Java?**
Java's design philosophy favors simplicity and clarity. Allowing multiple return values directly could complicate the language and lead to less readable code. The existing methods provide sufficient flexibility while maintaining code clarity.
**Q: Is using a Map a good way to return multiple values?**
While technically possible, using a Map is generally not recommended unless the values are logically related as key-value pairs. For returning unrelated values, other methods like custom objects or Pair are more suitable.
**Q: What are the performance implications of each method?**
Arrays are generally the most performant, followed by output parameters. Custom objects and the Pair class might have a slight overhead due to object creation, but this is usually negligible unless the method is called very frequently in performance-critical sections of your code.
Understanding the nuances of each approach allows you to write more effective and maintainable Java code. Choosing wisely enhances your projects, ensuring they remain clear, efficient, and easy to understand. The best method depends on your specific requirements, so experiment and find what works best for you. Remember, clear and concise code leads to fewer bugs and easier collaboration. You can also explore other advanced Java concepts by visiting [our article on advanced Java techniques](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c). Dive deeper, practice regularly, and continue refining your skills to become a proficient Java developer.

Question & Answer :
I am trying to return 2 values from a Java method but I get these errors. Here is my code:

// Method code public static int something(){ int number1 = 1; int number2 = 2; return number1, number2; } // Main method code public static void main(String[] args) { something(); System.out.println(number1 + number2); } 

Error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement at assignment.Main.something(Main.java:86) at assignment.Main.main(Main.java:53) 

Java Result: 1

Instead of returning an array that contains the two values or using a generic Pair class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.

Note: A generic Pair class, as proposed in some of the other answers here, also gives you type safety, but doesn’t convey what the result represents.

Example (which doesn’t use really meaningful names):

final class MyResult { private final int first; private final int second; public MyResult(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // ... public static MyResult something() { int number1 = 1; int number2 = 2; return new MyResult(number1, number2); } public static void main(String[] args) { MyResult result = something(); System.out.println(result.getFirst() + result.getSecond()); }