0

For example if I had the method:

public static String exampleMethod(String a, String b) {
    }

Is it possible to make the same method with the same name like this:

public static String exampleMethod(String a, int b) {
    }

And is it possible for exampleMethod to return either a int or a string?

1
  • 1
    If only there was a way to easily find out! Commented Aug 18, 2020 at 12:37

3 Answers 3

1
  1. Yes, it's called method overloading.
  2. No, you cannot return different return types from the same method. The best you can do is to return both and have the caller check which you've returned. i.e. create a tuple class to store the String and Integer: Tuple<String, Integer>, and return it from your method.
Sign up to request clarification or add additional context in comments.

Comments

0

Yes, it's called method overloading. A method can only have one return type, but by overloading, each version of the method can have its own return type.

Comments

0

This is called Method Overloading. If you want your method to accept two strings or a string and an int:

public static String exampleMethod(String a, int b) {
    }

If you want it to accept two strings:

public static String exampleMethod(String a, String b) {
    }

etc... Unfortunately, one method cannot have two return types but when overloading, you can change the return type. For example:

 public static int exampleMethod(String a, int b) {
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.