How to write Java function that returns values of multiple data types?

You could technically do this:

public <T> T doWork()
{
   if(codition)
   {
      return (T) new Integer(1);
   }
   else
   {
      return (T) Boolean.FALSE;
   }
}

Then this code would compile:

int x = doWork(); // the condition evaluates to true
boolean test = doWork();

But you could most certainly encounter runtime exceptions if the method returns the wrong type. You also must return objects instead of primitives because T is erased to java.lang.Object, which means the returned type must extend Object (i.e. be an object). The above example makes use of autoboxing to achieve a primitive return type.

I certainly wouldn't recommend this approach because IMO you need to evaluate your use of exception handling. You catch exceptions in exceptional cases if you can do something with that exception (i.e. recover, persist, retry, etc.). Exceptions are an exception to the expected workflow, not a part of it.


no. the best you can do is return on instance of a class that handles all the things you might want to return.

something like

public class ReturnObj {
   public bool yesno; // yes or no
   public int val; // for int values
   public String mode; // mode describing what you returned, which the caller will need to understand.
}

obviously, you need to play with the names....

Also, this seems like a code smell. You might be able to remove the need to do something like this by qualifying what path you want outside of your function, and then call a specific function to get a boolean or a specific function to get an int, depending on the qualification.


No, you can't do that in Java.

You could return an Object though. And by returning an object you could technically return a derived class such as java.lang.Integer or java.lang.Boolean. However, I don't think it's the best idea.