Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return two variables from one method

How to write the following code correctly?

public String toString(int[] position, int xOffset, int yOffset) {
    String postn = String.format("[%d,%d]", position[0], position[1]);
    String movm = String.format("[%d,%d]", xOffset, yOffset);

    return (postn, movm);
}

Following error came up

movm cannot be returned.
like image 593
Lbert Hartanto Avatar asked Oct 27 '14 10:10

Lbert Hartanto


People also ask

Can a method return two variables?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

Can we return 2 values from a function in Java?

Java doesn't support multi-value returns. We can use following solutions to return multiple values. We can return an array in Java. Below is a Java program to demonstrate the same.

Can we return 2 variables in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.


1 Answers

When using Java 8 you could make use of the Pair class.

private static Pair<String, String> foo (/* some params */) {
    final String val1 = "";  // some calculation
    final String val2 = "";  // some other calculation

    return new Pair<>(val1, val2);
}

Otherwise simply return an array.

like image 72
ifloop Avatar answered Sep 24 '22 06:09

ifloop