Your Search Bar For Shrewd Tips

How To Return Multiple Values In Java


How To Return Multiple Values In Java

When developing Java applications, there are many scenarios where you may need to return multiple values from a method. Unlike some languages, Java methods are designed to return a single value. However, Java offers several effective techniques to work around this limitation and enable methods to return multiple values. In this comprehensive guide, we'll explore various methods to return multiple values in Java, including their advantages and best use cases.

Using a Custom Class to Return Multiple Values

One of the most straightforward and type-safe ways to return multiple values in Java is by creating a custom class that encapsulates all the values you wish to return. This approach is clean, maintainable, and aligns well with object-oriented principles.

Here's how you can implement this method:

  • Define a class with fields representing each value you want to return.
  • Create an instance of this class inside your method, set the values, and return it.
  • Access the individual values through getter methods or public fields.

Example:


public 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 Main {
    public static Result getMultipleValues() {
        int number = 42;
        String message = "Hello";
        return new Result(number, message);
    }

    public static void main(String[] args) {
        Result result = getMultipleValues();
        System.out.println("Number: " + result.getValue1());
        System.out.println("Message: " + result.getValue2());
    }
}
    

This method ensures type safety and clarity, especially when dealing with complex data structures.

Using Arrays to Return Multiple Values

Another simple approach is to return an array containing multiple values. While this method is quick and easy, it lacks type safety, as all array elements are of the same type. Use this approach when the values are of the same type or when type safety is not a concern.

Example:


public class Main {
    public static int[] getMultipleValues() {
        int[] values = new int[2];
        values[0] = 10;
        values[1] = 20;
        return values;
    }

    public static void main(String[] args) {
        int[] results = getMultipleValues();
        System.out.println("First value: " + results[0]);
        System.out.println("Second value: " + results[1]);
    }
}
    

Limitations of this method include:

  • All returned elements must be of the same type.
  • Less descriptive — the meaning of each array index is not explicit.
  • Potential for index errors if not carefully managed.

Using Collections (e.g., List or Map)

Collections like List or Map provide flexible ways to return multiple values. They are especially useful when the number of values might vary or when you want to associate values with keys.

Example using a List:


import java.util.Arrays;
import java.util.List;

public class Main {
    public static List getMultipleValues() {
        int number = 5;
        String message = "Success";
        return Arrays.asList(number, message);
    }

    public static void main(String[] args) {
        List results = getMultipleValues();
        int number = (int) results.get(0);
        String message = (String) results.get(1);
        System.out.println("Number: " + number);
        System.out.println("Message: " + message);
    }
}
    

Using a Map is similar but allows key-value pairs, making the data more descriptive:


import java.util.HashMap;
import java.util.Map;

public class Main {
    public static Map getMultipleValues() {
        Map data = new HashMap<>();
        data.put("count", 10);
        data.put("status", "OK");
        return data;
    }

    public static void main(String[] args) {
        Map results = getMultipleValues();
        System.out.println("Count: " + results.get("count"));
        System.out.println("Status: " + results.get("status"));
    }
}
    

Advantages of collections include flexibility and clarity, especially when using descriptive keys. However, they require type casting and may introduce overhead.

Using Wrapper Classes and JavaFX Pair or AbstractMap.SimpleEntry

Java provides utility classes like javafx.util.Pair or AbstractMap.SimpleEntry to encapsulate two related objects conveniently. These are suitable when returning exactly two values.

Example with Pair:


import javafx.util.Pair;

public class Main {
    public static Pair getValues() {
        return new Pair<>(100, "Success");
    }

    public static void main(String[] args) {
        Pair result = getValues();
        System.out.println("Number: " + result.getKey());
        System.out.println("Message: " + result.getValue());
    }
}
    

Note: javafx.util.Pair is part of JavaFX, which may not be available in all environments. Alternatively, you can create your own Pair class or use third-party libraries like Apache Commons Lang.

Using Java Records (Java 14+) for Immutable Data Carriers

Java Records, introduced in Java 14, provide a concise way to create immutable data carriers. They are perfect for returning multiple related values in a clean and type-safe manner.

Example:


public record Result(int number, String message) {}

public class Main {
    public static Result getValues() {
        return new Result(200, "OK");
    }

    public static void main(String[] args) {
        Result result = getValues();
        System.out.println("Number: " + result.number());
        System.out.println("Message: " + result.message());
    }
}
    

Using records simplifies code and enhances readability, especially when dealing with data transfer objects or simple aggregations.

Choosing the Right Method for Your Scenario

When deciding which technique to use for returning multiple values in Java, consider the following factors:

  • Complexity of Data: Use custom classes or records for complex or multiple related data items.
  • Number of Values: For just two values, JavaFX Pair or AbstractMap.SimpleEntry are convenient.
  • Type Safety: Custom classes, records, and well-structured collections preserve type safety.
  • Readability: Custom classes and records make code more understandable.
  • Performance: Arrays and collections may introduce minimal overhead, but are usually acceptable.

Conclusion

Returning multiple values from a method in Java is a common challenge that can be effectively addressed using various techniques. Whether you prefer creating custom classes, using collections, leveraging utility classes like Pair, or utilizing modern Java features like records, each method has its own advantages suited to different scenarios. Carefully consider your application's requirements, data complexity, and future maintainability when choosing the best approach.

By understanding these techniques, Java developers can write cleaner, more efficient, and more expressive code that accurately conveys multiple return values, ultimately leading to better software design and improved code quality.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →