Forums Register Login
Static Methods
does Java allow someone to return more than one answer or number when using the "return" function in a static method.

for example:

if (a>b && b>c)

a >b

return a;
return b;

can you actually do this?

If you mean "can I return one thing or another from a method?" like this:

then the answer is yes.

If you mean "Can I return two things from a method?" then the answer is also yes:

If you mean "can I call return twice to return two things?" then the answer is no. The reason is shown in the first example - return will 'exit' the method.
[ March 08, 2005: Message edited by: Paul Sturrock ]
Another trick to use (and, yes people, feel free to tell me that this isn't a good design... ) is output parameters. In C, this is typically doen with pointers-to-pointers, but in Java, we don't have pointers. But we do have arrays.

As I say, this is generally not good programming practice. Usually, I use this as is only a temporary approach, and wind up refactoring the method call into two methods or returning a complex type down the road.
Yes, using array types to store individual return values which must be picked off from the correct indices isn't good practice (unless it's an obvious one like coordinates or something). As Joel said, it's better to define a "complex" type that holds your values and exposes them in a more meaningful manner. Then, your API tells you what it's doing rather than requiring someone to read your documentation to figure out which index to use to get what value. Also, if you do ever need to add stuff to the return value, it's much easier, especially if you were to want to add something into the middle of the array.

Look at the interface called Serializable. Here is how I would use it.

Class A implements Serializable

Class B implements Serializable

Class C implements Serializable

public Serializable doSomething(Object E)
if (E instanceof A)
return (A)E;
else if(E instanceof B)
return (B)E;


Also you can do this using the Object class. The only stipulation I would say is that you must use the "instanceof" facility.

Best of luck,

Russ, using Serializable doesn't buy you anything in your example, you could simply use Object as return type.

Type cases (your if statements using instanceof) are a bad idea, though - they fly in the face of OO programming. It's much better to use polymorphic behaviour instead.
No one can make you feel inferior without your consent - Eleanor Roosevelt. tiny ad:
Become a Java guru with IntelliJ IDEA

This thread has been viewed 696 times.

All times above are in ranch (not your local) time.
The current ranch time is
Mar 23, 2019 06:17:08.