Home >Java >javaTutorial >How to Return Multiple Values from a Java Method?

How to Return Multiple Values from a Java Method?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 18:46:39890browse

How to Return Multiple Values from a Java Method?

Returning Multiple Values from a Java Method

In Java, methods typically return a single value of a specific type. However, sometimes, a method may need to return multiple values.

Problem Description

The provided code aims to return two integers, number1 and number2, from the something() method. However, the compilation fails with an error message indicating a missing return statement.

Solution

While the proposed approaches, such as creating arrays or using generic Pair classes, provide solutions to the problem, they may not be optimal in terms of type safety and readability. Instead, creating a custom class representing the desired result is a preferred approach.

Custom Class for Result

Consider creating a class named MyResult that encapsulates both integers:

<code class="java">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;
    }
}</code>

Updated Method Signature and Implementation

Modify the something() method to return an instance of MyResult:

<code class="java">public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}</code>

Main Method Usage

In the main() method, obtain the returned values from the MyResult instance:

<code class="java">public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}</code>

This approach provides type safety and makes the program easier to understand by clearly representing the intended result.

The above is the detailed content of How to Return Multiple Values from a Java Method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn