Eragon20
Eragon20

Reputation: 483

java method return multiple values

I have a method that I wish to call twice in a program. When I call it first, I do not want it to return any value, but when I call it in a different class, I want it to return a string output.

It seems like rather a waste to copy and paste and entire method to add just one return line the for this second instance.

I considered adding a parameter location and then saying:

if (location.equals("location1")) {
    return null;
}
else {
    return output;
}

But I really do not want to return anything, even null, the first time I reference this method.

Is this possible?

Upvotes: 2

Views: 1649

Answers (4)

PNS
PNS

Reputation: 19895

Java is a strongly typed language. All methods have a return type (including void, which means return nothing).

It is not possible to have method returning nothing if its type is not void and that cannot be changed. This is for a good reason, too: methods that return values are typically used for populating parameters of certain data types.

For example, consider the method

public abstract int calculate();

which is called by an application, for calculating a value, which is saved in a parameter for subsequent use, e.g.

int result = calculate();

What would go into result, if there was an option to "not return anything" from the calculate() method?

For this and numerous other reasons, a method must always return a value of a specific data type, or be of type void and this is enforced by the Java compiler. If it does return a value, it can be used or ignored, according to the needs of the calling application.

The use of the java.util.Optional class, introduced in Java 8 and suggested in another answer, is probably not the most suitable approach for use cases like the question above. Having said that, a nice discussion about Optional can be found in another StackOverlow question.

Upvotes: 1

Vasu
Vasu

Reputation: 22384

You can use Optional (from Java8) exactly for this purpose as shown below:

public Optional<String> myMethod(String location) {
   if (location.equals("location1")) {
     return Optional.empty();//returns empty Optional object
   } else {
     return Optional.of(output);//returns String wrapped by Optional
   }
}

I suggest you look at the java.util.Optional API here & below text (emphasis mine).

java.util.Optional container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Upvotes: 3

Mikhail Antonov
Mikhail Antonov

Reputation: 1367

Why don't you just ignore the return value in first "location"? Or if method needs to know the context just pass a parameter to it and ignore the return value in first location? Like that:

public String myMethod(boolean calledFromFirstLocation) {
    if (calledFromFirstLocation) {
        // do something specific for 1st location
        return null; // ignore it later
    } else {
        return "output";
    }
}

Then just call it like:

// return value ignored, method knows it is being called from location1
myMethod(true);
// should print "output"
System.out.println(myMethod(false));

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140299

If your method has String as its return type, it must always return a String (or null, or throw an exception). From JLS Sec 8.4.7:

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

"Complete normally" is a slightly funny phrase if you are unfamiliar with it. Returning a value is not completing normally, believe it or not. From JLS Sec 14.1:

If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:

  • The break (§14.15), continue (§14.16), and return (§14.17) statements cause a transfer of control that may prevent normal completion of statements that contain them.

  • Evaluation of certain expressions may throw exceptions from the Java Virtual Machine (§15.6). An explicit throw (§14.18) statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.

Since you're not in a loop, you can't use break or continue; so, you always have to return a value or throw to avoid normal completion.

The easiest thing to do is just not to do anything with the return value where you call the method.

Upvotes: 2

Related Questions