Home > Java > javaTutorial > body text

How can I return multiple values from a Java method?

Susan Sarandon
Release: 2024-11-02 07:53:29
Original
989 people have browsed it

How can I return multiple values from a Java method?

Returning Multiple Values from Java Methods

Returning multiple values from a Java method presents a challenge if traditional methods are used. Attempting to return two values as demonstrated in the code below will result in a compilation error.

<code class="java">public static int something() {
    int number1 = 1;
    int number2 = 2;
    
    return number1, number2; // Compilation error: cannot return multiple values
}</code>
Copy after login

Overcoming the Limitation

To resolve this limitation, consider using a custom class to represent the result, rather than returning an array or using a generic Pair class. This approach not only ensures type safety, but also enhances code readability.

Example Implementation

<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;
    }
}

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());
}</code>
Copy after login

The above is the detailed content of How can I return multiple values from a Java method?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!