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
You don't need to create your own class to return two different values. Just use a HashMap like this:
You even have the benefit of type safety.
Return an Array Of Objects
I'm curious as to why nobody has come up with the more elegant callback solution. So instead of using a return type you use a handler passed into the method as an argument. The example below has the two contrasting approaches. I know which of the two is more elegant to me. :-)
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):
In my opinion the best is to create a new class which constructor is the function you need, e.g.:
Then simply use the constructor as you would use the function:
and you can use pR.sth1, pR.sth2 as "2 results of the function"
You can only return one value in Java, so the neatest way is like this:
Here's an updated version of your code: