How to write Java function that returns values of multiple data types?Hashmap holding different data types as values for instance Integer, String and ObjectJava, what if I want to return different types from function?How should I go about making a List method return a String value?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?Does Java support default parameter values?How do I determine whether an array contains a particular value in Java?How do I create a file and write to it in Java?How do I convert a String to an int in Java?

Full horizontal justification in table

How do you say “buy” in the sense of “believe”?

Mother abusing my finances

Under what law can the U.S. arrest International Criminal Court (ICC) judges over war crimes probe?

Would jet fuel for an F-16 or F-35 be producible during WW2?

Why is desire the root of suffering?

Plot twist where the antagonist wins

Confirmation for file / directory move operation

General purpose replacement for enum with FlagsAttribute

Employer asking for online access to bank account - Is this a scam?

Is there a public standard for 8 and 10 character grid locators?

Where did Wilson state that the US would have to force access to markets with violence?

What are these arcade games in Ghostbusters 1984?

Identifying an object pointer by generating and using a unique ID

How to convert to standalone document a matrix table

When did God say "let all the angels of God worship him" as stated in Hebrews 1:6?

I unknowingly submitted plagiarised work

Is there a general effective method to solve Smullyan style Knights and Knaves problems? Is the truth table method the most appropriate one?

What is the most important source of natural gas? coal, oil or other?

Apparent Ring of Craters on the Moon

Tic-tac-toe for the terminal, written in C

Is healing by fire possible?

How do I align equations in three columns, justified right, center and left?

ESTA/WVP - leaving US within 90 days, then staying in DR



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


Hashmap holding different data types as values for instance Integer, String and ObjectJava, what if I want to return different types from function?How should I go about making a List method return a String value?Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?How do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to get an enum value from a string value in Java?Does Java support default parameter values?How do I determine whether an array contains a particular value in Java?How do I create a file and write to it in Java?How do I convert a String to an int in Java?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








16















For example, I want to create a function that can return any number (negative, zero, or positive).



However, based on certain exceptions, I'd like the function to return Boolean FALSE



Is there a way to write a function that can return an int or a Boolean?




Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should throw some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)



public class Quad 

public static void main (String[] args)

double a, b, c;

a=1; b=-7; c=12;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0
System.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0


// "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
a=4; b=4; c=16;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = NaN
System.out.println("x = " + quadratic(a, b, c, -1)); // x = NaN



public static double quadratic(double a, double b, double c, int polarity)

double x = b*b - 4*a*c;

// When x < 0, Math.sqrt(x) retruns NaN
if (x < 0)
/*
throw exception!
I understand this code can be adjusted to accommodate
imaginary numbers, but for the sake of this example,
let's just have this function throw an exception and
say the coefficients are invalid
*/


return (-b + Math.sqrt(x) * polarity) / (2*a);













share|improve this question



















  • 2





    You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

    – maaartinus
    Feb 10 '11 at 3:04






  • 2





    Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

    – duffymo
    Feb 10 '11 at 3:05

















16















For example, I want to create a function that can return any number (negative, zero, or positive).



However, based on certain exceptions, I'd like the function to return Boolean FALSE



Is there a way to write a function that can return an int or a Boolean?




Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should throw some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)



public class Quad 

public static void main (String[] args)

double a, b, c;

a=1; b=-7; c=12;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0
System.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0


// "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
a=4; b=4; c=16;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = NaN
System.out.println("x = " + quadratic(a, b, c, -1)); // x = NaN



public static double quadratic(double a, double b, double c, int polarity)

double x = b*b - 4*a*c;

// When x < 0, Math.sqrt(x) retruns NaN
if (x < 0)
/*
throw exception!
I understand this code can be adjusted to accommodate
imaginary numbers, but for the sake of this example,
let's just have this function throw an exception and
say the coefficients are invalid
*/


return (-b + Math.sqrt(x) * polarity) / (2*a);













share|improve this question



















  • 2





    You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

    – maaartinus
    Feb 10 '11 at 3:04






  • 2





    Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

    – duffymo
    Feb 10 '11 at 3:05













16












16








16


2






For example, I want to create a function that can return any number (negative, zero, or positive).



However, based on certain exceptions, I'd like the function to return Boolean FALSE



Is there a way to write a function that can return an int or a Boolean?




Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should throw some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)



public class Quad 

public static void main (String[] args)

double a, b, c;

a=1; b=-7; c=12;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0
System.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0


// "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
a=4; b=4; c=16;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = NaN
System.out.println("x = " + quadratic(a, b, c, -1)); // x = NaN



public static double quadratic(double a, double b, double c, int polarity)

double x = b*b - 4*a*c;

// When x < 0, Math.sqrt(x) retruns NaN
if (x < 0)
/*
throw exception!
I understand this code can be adjusted to accommodate
imaginary numbers, but for the sake of this example,
let's just have this function throw an exception and
say the coefficients are invalid
*/


return (-b + Math.sqrt(x) * polarity) / (2*a);













share|improve this question
















For example, I want to create a function that can return any number (negative, zero, or positive).



However, based on certain exceptions, I'd like the function to return Boolean FALSE



Is there a way to write a function that can return an int or a Boolean?




Ok, so this has received a lot of responses. I understand I'm simply approaching the problem incorrectly and I should throw some sort of Exception in the method. To get a better answer, I'm going to provide some example code. Please don't make fun :)



public class Quad 

public static void main (String[] args)

double a, b, c;

a=1; b=-7; c=12;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = 4.0
System.out.println("x = " + quadratic(a, b, c, -1)); // x = 3.0


// "invalid" coefficients. Let's throw an exception here. How do we handle the exception?
a=4; b=4; c=16;
System.out.println("x = " + quadratic(a, b, c, 1)); // x = NaN
System.out.println("x = " + quadratic(a, b, c, -1)); // x = NaN



public static double quadratic(double a, double b, double c, int polarity)

double x = b*b - 4*a*c;

// When x < 0, Math.sqrt(x) retruns NaN
if (x < 0)
/*
throw exception!
I understand this code can be adjusted to accommodate
imaginary numbers, but for the sake of this example,
let's just have this function throw an exception and
say the coefficients are invalid
*/


return (-b + Math.sqrt(x) * polarity) / (2*a);










java methods overloading






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 11 '11 at 5:01







maček

















asked Feb 10 '11 at 2:43









mačekmaček

54k29146182




54k29146182







  • 2





    You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

    – maaartinus
    Feb 10 '11 at 3:04






  • 2





    Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

    – duffymo
    Feb 10 '11 at 3:05












  • 2





    You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

    – maaartinus
    Feb 10 '11 at 3:04






  • 2





    Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

    – duffymo
    Feb 10 '11 at 3:05







2




2





You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

– maaartinus
Feb 10 '11 at 3:04





You've got already quite a few answers, so you can see it's possible, but not nice. I'd recommend you to explain what you need it for. Then you'll most probably get a nicer solution. Btw., exception could be represented by throwing an exception, too. Returning Boolean.FALSE and never returning Boolean.TRUE is a code smell, consider returning Integer with null returned instead of FALSE.

– maaartinus
Feb 10 '11 at 3:04




2




2





Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

– duffymo
Feb 10 '11 at 3:05





Using the return value is C-style programming. Not that there's anything wrong with that, but consider exceptions. This is what they're made for.

– duffymo
Feb 10 '11 at 3:05












10 Answers
10






active

oldest

votes


















13














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.






share|improve this answer






























    11














    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.






    share|improve this answer






























      6














      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.






      share|improve this answer

























      • You should probably use an Enum, not a String

        – Solomon Ucko
        Dec 22 '16 at 0:46


















      4














      IEEE Floating Point



      Most languages will handle your specific example without Exceptions or union types because IEEE floating point includes a representation for NaN. In Java, use Double.NaN:



      public static double quadratic(double a, double b, double c, int polarity) 
      double x = b*b - 4*a*c;

      // When x < 0, Math.sqrt(x) retruns NaN
      if (x < 0)
      return Double.NaN;

      return (-b + Math.sqrt(x) * polarity) / (2*a);



      That produces your exact output that you wanted:



      x = 4.0
      x = 3.0
      x = NaN
      x = NaN


      Exceptions



      Exceptions are The Old Java Way of solving similar problems:



      public static double quadratic(double a, double b, double c, int polarity) 
      double x = b*b - 4*a*c;
      // When x < 0, Math.sqrt(x) returns NaN
      if (x < 0)
      throw new Exception("NaN")

      return (-b + Math.sqrt(x) * polarity) / (2*a);



      Here's your client code for an Exception.



      a=1; b=-7; c=12;

      // x = 4.0
      try
      System.out.println("x = " + quadratic(a, b, c, 1));
      catch (Exception iae)
      System.out.println("Oopsie: " + iae.getMessage());


      // x = 3.0
      try
      System.out.println("x = " + quadratic(a, b, c, -1));
      catch (Exception iae)
      System.out.println("Oopsie: " + iae.getMessage());


      // "invalid" coefficients.
      a=4; b=4; c=16;

      // Oopsie: NaN
      try
      System.out.println("x = " + quadratic(a, b, c, 1));
      catch (Exception iae)
      System.out.println("Oopsie: " + iae.getMessage());


      // Oopsie: NaN
      try
      System.out.println("x = " + quadratic(a, b, c, -1));
      catch (Exception iae)
      System.out.println("Oopsie: " + iae.getMessage());



      Union Types



      To truly pass or return unrelated types to or from a method, you want Union types which Java does not really support. But Paguro provides Union Types which you can use in Java like this (using Or):



      public static Or<Double,String> quadratic(double a, double b,
      double c, int polarity)
      double x = b*b - 4*a*c;

      // When x < 0, Math.sqrt(x) retruns NaN
      if (x < 0)
      return Or.bad("NaN");

      return Or.good((-b + Math.sqrt(x) * polarity) / (2*a));


      @Test public void testQuadradic()
      double a, b, c;
      a=1; b=-7; c=12;

      // x = Good(4.0)
      System.out.println("x = " + quadratic(a, b, c, 1));

      // x = 3.0
      System.out.println(
      (String) quadratic(a, b, c, -1)
      .match(good -> "x = " + good,
      bad -> "Oopsie: " + bad));

      // "invalid" coefficients.
      a=4; b=4; c=16;

      // x = Bad("NaN")
      System.out.println("x = " + quadratic(a, b, c, 1));

      // Oopsie: NaN
      System.out.println(
      (String) quadratic(a, b, c, -1)
      .match(good -> "x = " + good,
      bad -> "Oopsie: " + bad));



      Conclusion



      For your specific example, just use Floating Point. For a more general solution, I find union types more useful than Exceptions. You can use union types as arguments to a method that might take two different inputs which have no common interface or ancestor. They are also more friendly to Functional Programming.






      share|improve this answer
































        3














        Write a function that returns an Object. Have it either return the Boolean or Integer wrapper objects. Then use instanceof to figure out which to use.






        share|improve this answer






























          1














          No, one return reference to a customer.



          You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.



          But if I was a user I'd think your design was confusing.






          share|improve this answer






























            1














            my teacher had a cool idea for a tryParse C# like method in java hope it helps



            import java.util.Scanner;

            public class Program
            static Scanner scanner = new Scanner(System.in);
            public static void main(String[] args)
            System.out.println("Enter number");
            String input = scanner.next();
            int[] num =0;
            if(tryParse(input,num))
            System.out.println(num[0] * num[0]);

            static boolean tryParse(String inputString,int[] outputInt)
            try
            outputInt[0] = Integer.parseInt(inputString);
            return true;
            catch(Exception e)
            return false;








            share|improve this answer






























              0














              This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.






              share|improve this answer






























                -1














                I would say it is possible. But not directly.



                I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.



                Add your values to a Map like below. And get it with its key!



                public static HashMap returnAnyType()
                String x = "This";
                int a = 9;

                HashMap<String, Object> myMap = new HashMap();
                myMap.put("stringVal", x);
                myMap.put("intVal", a);
                return myMap;


                String theStringFromTheMap = (String) returnAnyType().get("stringVal");
                int theIntFromTheMap = (Integer) returnAnyType().get("intVal");

                System.out.println("String : " + theStringFromTheMap + " is great !");
                System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));



                Output (both are returned from same method):




                String : This is great!
                Integer: 19



                Note:

                This is not a good practice. But it helps sometimes when it is needed!






                share|improve this answer

























                • Why down voted ? Please explain !

                  – smilyface
                  Dec 30 '15 at 9:35











                • I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                  – Solomon Ucko
                  Dec 22 '16 at 1:10












                • stackoverflow.com/a/19044187/2086966 Please go through

                  – smilyface
                  Mar 24 at 7:29


















                -2














                inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.






                share|improve this answer























                  Your Answer






                  StackExchange.ifUsing("editor", function ()
                  StackExchange.using("externalEditor", function ()
                  StackExchange.using("snippets", function ()
                  StackExchange.snippets.init();
                  );
                  );
                  , "code-snippets");

                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "1"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4952856%2fhow-to-write-java-function-that-returns-values-of-multiple-data-types%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  10 Answers
                  10






                  active

                  oldest

                  votes








                  10 Answers
                  10






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  13














                  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.






                  share|improve this answer



























                    13














                    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.






                    share|improve this answer

























                      13












                      13








                      13







                      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.






                      share|improve this answer













                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 10 '11 at 2:46









                      Pablo Santa CruzPablo Santa Cruz

                      138k27204256




                      138k27204256























                          11














                          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.






                          share|improve this answer



























                            11














                            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.






                            share|improve this answer

























                              11












                              11








                              11







                              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.






                              share|improve this answer













                              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.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Feb 10 '11 at 4:45









                              hisdrewnesshisdrewness

                              6,44221528




                              6,44221528





















                                  6














                                  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.






                                  share|improve this answer

























                                  • You should probably use an Enum, not a String

                                    – Solomon Ucko
                                    Dec 22 '16 at 0:46















                                  6














                                  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.






                                  share|improve this answer

























                                  • You should probably use an Enum, not a String

                                    – Solomon Ucko
                                    Dec 22 '16 at 0:46













                                  6












                                  6








                                  6







                                  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.






                                  share|improve this answer















                                  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.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Feb 10 '11 at 2:53

























                                  answered Feb 10 '11 at 2:46









                                  hvgotcodeshvgotcodes

                                  94.9k21175224




                                  94.9k21175224












                                  • You should probably use an Enum, not a String

                                    – Solomon Ucko
                                    Dec 22 '16 at 0:46

















                                  • You should probably use an Enum, not a String

                                    – Solomon Ucko
                                    Dec 22 '16 at 0:46
















                                  You should probably use an Enum, not a String

                                  – Solomon Ucko
                                  Dec 22 '16 at 0:46





                                  You should probably use an Enum, not a String

                                  – Solomon Ucko
                                  Dec 22 '16 at 0:46











                                  4














                                  IEEE Floating Point



                                  Most languages will handle your specific example without Exceptions or union types because IEEE floating point includes a representation for NaN. In Java, use Double.NaN:



                                  public static double quadratic(double a, double b, double c, int polarity) 
                                  double x = b*b - 4*a*c;

                                  // When x < 0, Math.sqrt(x) retruns NaN
                                  if (x < 0)
                                  return Double.NaN;

                                  return (-b + Math.sqrt(x) * polarity) / (2*a);



                                  That produces your exact output that you wanted:



                                  x = 4.0
                                  x = 3.0
                                  x = NaN
                                  x = NaN


                                  Exceptions



                                  Exceptions are The Old Java Way of solving similar problems:



                                  public static double quadratic(double a, double b, double c, int polarity) 
                                  double x = b*b - 4*a*c;
                                  // When x < 0, Math.sqrt(x) returns NaN
                                  if (x < 0)
                                  throw new Exception("NaN")

                                  return (-b + Math.sqrt(x) * polarity) / (2*a);



                                  Here's your client code for an Exception.



                                  a=1; b=-7; c=12;

                                  // x = 4.0
                                  try
                                  System.out.println("x = " + quadratic(a, b, c, 1));
                                  catch (Exception iae)
                                  System.out.println("Oopsie: " + iae.getMessage());


                                  // x = 3.0
                                  try
                                  System.out.println("x = " + quadratic(a, b, c, -1));
                                  catch (Exception iae)
                                  System.out.println("Oopsie: " + iae.getMessage());


                                  // "invalid" coefficients.
                                  a=4; b=4; c=16;

                                  // Oopsie: NaN
                                  try
                                  System.out.println("x = " + quadratic(a, b, c, 1));
                                  catch (Exception iae)
                                  System.out.println("Oopsie: " + iae.getMessage());


                                  // Oopsie: NaN
                                  try
                                  System.out.println("x = " + quadratic(a, b, c, -1));
                                  catch (Exception iae)
                                  System.out.println("Oopsie: " + iae.getMessage());



                                  Union Types



                                  To truly pass or return unrelated types to or from a method, you want Union types which Java does not really support. But Paguro provides Union Types which you can use in Java like this (using Or):



                                  public static Or<Double,String> quadratic(double a, double b,
                                  double c, int polarity)
                                  double x = b*b - 4*a*c;

                                  // When x < 0, Math.sqrt(x) retruns NaN
                                  if (x < 0)
                                  return Or.bad("NaN");

                                  return Or.good((-b + Math.sqrt(x) * polarity) / (2*a));


                                  @Test public void testQuadradic()
                                  double a, b, c;
                                  a=1; b=-7; c=12;

                                  // x = Good(4.0)
                                  System.out.println("x = " + quadratic(a, b, c, 1));

                                  // x = 3.0
                                  System.out.println(
                                  (String) quadratic(a, b, c, -1)
                                  .match(good -> "x = " + good,
                                  bad -> "Oopsie: " + bad));

                                  // "invalid" coefficients.
                                  a=4; b=4; c=16;

                                  // x = Bad("NaN")
                                  System.out.println("x = " + quadratic(a, b, c, 1));

                                  // Oopsie: NaN
                                  System.out.println(
                                  (String) quadratic(a, b, c, -1)
                                  .match(good -> "x = " + good,
                                  bad -> "Oopsie: " + bad));



                                  Conclusion



                                  For your specific example, just use Floating Point. For a more general solution, I find union types more useful than Exceptions. You can use union types as arguments to a method that might take two different inputs which have no common interface or ancestor. They are also more friendly to Functional Programming.






                                  share|improve this answer





























                                    4














                                    IEEE Floating Point



                                    Most languages will handle your specific example without Exceptions or union types because IEEE floating point includes a representation for NaN. In Java, use Double.NaN:



                                    public static double quadratic(double a, double b, double c, int polarity) 
                                    double x = b*b - 4*a*c;

                                    // When x < 0, Math.sqrt(x) retruns NaN
                                    if (x < 0)
                                    return Double.NaN;

                                    return (-b + Math.sqrt(x) * polarity) / (2*a);



                                    That produces your exact output that you wanted:



                                    x = 4.0
                                    x = 3.0
                                    x = NaN
                                    x = NaN


                                    Exceptions



                                    Exceptions are The Old Java Way of solving similar problems:



                                    public static double quadratic(double a, double b, double c, int polarity) 
                                    double x = b*b - 4*a*c;
                                    // When x < 0, Math.sqrt(x) returns NaN
                                    if (x < 0)
                                    throw new Exception("NaN")

                                    return (-b + Math.sqrt(x) * polarity) / (2*a);



                                    Here's your client code for an Exception.



                                    a=1; b=-7; c=12;

                                    // x = 4.0
                                    try
                                    System.out.println("x = " + quadratic(a, b, c, 1));
                                    catch (Exception iae)
                                    System.out.println("Oopsie: " + iae.getMessage());


                                    // x = 3.0
                                    try
                                    System.out.println("x = " + quadratic(a, b, c, -1));
                                    catch (Exception iae)
                                    System.out.println("Oopsie: " + iae.getMessage());


                                    // "invalid" coefficients.
                                    a=4; b=4; c=16;

                                    // Oopsie: NaN
                                    try
                                    System.out.println("x = " + quadratic(a, b, c, 1));
                                    catch (Exception iae)
                                    System.out.println("Oopsie: " + iae.getMessage());


                                    // Oopsie: NaN
                                    try
                                    System.out.println("x = " + quadratic(a, b, c, -1));
                                    catch (Exception iae)
                                    System.out.println("Oopsie: " + iae.getMessage());



                                    Union Types



                                    To truly pass or return unrelated types to or from a method, you want Union types which Java does not really support. But Paguro provides Union Types which you can use in Java like this (using Or):



                                    public static Or<Double,String> quadratic(double a, double b,
                                    double c, int polarity)
                                    double x = b*b - 4*a*c;

                                    // When x < 0, Math.sqrt(x) retruns NaN
                                    if (x < 0)
                                    return Or.bad("NaN");

                                    return Or.good((-b + Math.sqrt(x) * polarity) / (2*a));


                                    @Test public void testQuadradic()
                                    double a, b, c;
                                    a=1; b=-7; c=12;

                                    // x = Good(4.0)
                                    System.out.println("x = " + quadratic(a, b, c, 1));

                                    // x = 3.0
                                    System.out.println(
                                    (String) quadratic(a, b, c, -1)
                                    .match(good -> "x = " + good,
                                    bad -> "Oopsie: " + bad));

                                    // "invalid" coefficients.
                                    a=4; b=4; c=16;

                                    // x = Bad("NaN")
                                    System.out.println("x = " + quadratic(a, b, c, 1));

                                    // Oopsie: NaN
                                    System.out.println(
                                    (String) quadratic(a, b, c, -1)
                                    .match(good -> "x = " + good,
                                    bad -> "Oopsie: " + bad));



                                    Conclusion



                                    For your specific example, just use Floating Point. For a more general solution, I find union types more useful than Exceptions. You can use union types as arguments to a method that might take two different inputs which have no common interface or ancestor. They are also more friendly to Functional Programming.






                                    share|improve this answer



























                                      4












                                      4








                                      4







                                      IEEE Floating Point



                                      Most languages will handle your specific example without Exceptions or union types because IEEE floating point includes a representation for NaN. In Java, use Double.NaN:



                                      public static double quadratic(double a, double b, double c, int polarity) 
                                      double x = b*b - 4*a*c;

                                      // When x < 0, Math.sqrt(x) retruns NaN
                                      if (x < 0)
                                      return Double.NaN;

                                      return (-b + Math.sqrt(x) * polarity) / (2*a);



                                      That produces your exact output that you wanted:



                                      x = 4.0
                                      x = 3.0
                                      x = NaN
                                      x = NaN


                                      Exceptions



                                      Exceptions are The Old Java Way of solving similar problems:



                                      public static double quadratic(double a, double b, double c, int polarity) 
                                      double x = b*b - 4*a*c;
                                      // When x < 0, Math.sqrt(x) returns NaN
                                      if (x < 0)
                                      throw new Exception("NaN")

                                      return (-b + Math.sqrt(x) * polarity) / (2*a);



                                      Here's your client code for an Exception.



                                      a=1; b=-7; c=12;

                                      // x = 4.0
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, 1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // x = 3.0
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, -1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // "invalid" coefficients.
                                      a=4; b=4; c=16;

                                      // Oopsie: NaN
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, 1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // Oopsie: NaN
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, -1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());



                                      Union Types



                                      To truly pass or return unrelated types to or from a method, you want Union types which Java does not really support. But Paguro provides Union Types which you can use in Java like this (using Or):



                                      public static Or<Double,String> quadratic(double a, double b,
                                      double c, int polarity)
                                      double x = b*b - 4*a*c;

                                      // When x < 0, Math.sqrt(x) retruns NaN
                                      if (x < 0)
                                      return Or.bad("NaN");

                                      return Or.good((-b + Math.sqrt(x) * polarity) / (2*a));


                                      @Test public void testQuadradic()
                                      double a, b, c;
                                      a=1; b=-7; c=12;

                                      // x = Good(4.0)
                                      System.out.println("x = " + quadratic(a, b, c, 1));

                                      // x = 3.0
                                      System.out.println(
                                      (String) quadratic(a, b, c, -1)
                                      .match(good -> "x = " + good,
                                      bad -> "Oopsie: " + bad));

                                      // "invalid" coefficients.
                                      a=4; b=4; c=16;

                                      // x = Bad("NaN")
                                      System.out.println("x = " + quadratic(a, b, c, 1));

                                      // Oopsie: NaN
                                      System.out.println(
                                      (String) quadratic(a, b, c, -1)
                                      .match(good -> "x = " + good,
                                      bad -> "Oopsie: " + bad));



                                      Conclusion



                                      For your specific example, just use Floating Point. For a more general solution, I find union types more useful than Exceptions. You can use union types as arguments to a method that might take two different inputs which have no common interface or ancestor. They are also more friendly to Functional Programming.






                                      share|improve this answer















                                      IEEE Floating Point



                                      Most languages will handle your specific example without Exceptions or union types because IEEE floating point includes a representation for NaN. In Java, use Double.NaN:



                                      public static double quadratic(double a, double b, double c, int polarity) 
                                      double x = b*b - 4*a*c;

                                      // When x < 0, Math.sqrt(x) retruns NaN
                                      if (x < 0)
                                      return Double.NaN;

                                      return (-b + Math.sqrt(x) * polarity) / (2*a);



                                      That produces your exact output that you wanted:



                                      x = 4.0
                                      x = 3.0
                                      x = NaN
                                      x = NaN


                                      Exceptions



                                      Exceptions are The Old Java Way of solving similar problems:



                                      public static double quadratic(double a, double b, double c, int polarity) 
                                      double x = b*b - 4*a*c;
                                      // When x < 0, Math.sqrt(x) returns NaN
                                      if (x < 0)
                                      throw new Exception("NaN")

                                      return (-b + Math.sqrt(x) * polarity) / (2*a);



                                      Here's your client code for an Exception.



                                      a=1; b=-7; c=12;

                                      // x = 4.0
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, 1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // x = 3.0
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, -1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // "invalid" coefficients.
                                      a=4; b=4; c=16;

                                      // Oopsie: NaN
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, 1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());


                                      // Oopsie: NaN
                                      try
                                      System.out.println("x = " + quadratic(a, b, c, -1));
                                      catch (Exception iae)
                                      System.out.println("Oopsie: " + iae.getMessage());



                                      Union Types



                                      To truly pass or return unrelated types to or from a method, you want Union types which Java does not really support. But Paguro provides Union Types which you can use in Java like this (using Or):



                                      public static Or<Double,String> quadratic(double a, double b,
                                      double c, int polarity)
                                      double x = b*b - 4*a*c;

                                      // When x < 0, Math.sqrt(x) retruns NaN
                                      if (x < 0)
                                      return Or.bad("NaN");

                                      return Or.good((-b + Math.sqrt(x) * polarity) / (2*a));


                                      @Test public void testQuadradic()
                                      double a, b, c;
                                      a=1; b=-7; c=12;

                                      // x = Good(4.0)
                                      System.out.println("x = " + quadratic(a, b, c, 1));

                                      // x = 3.0
                                      System.out.println(
                                      (String) quadratic(a, b, c, -1)
                                      .match(good -> "x = " + good,
                                      bad -> "Oopsie: " + bad));

                                      // "invalid" coefficients.
                                      a=4; b=4; c=16;

                                      // x = Bad("NaN")
                                      System.out.println("x = " + quadratic(a, b, c, 1));

                                      // Oopsie: NaN
                                      System.out.println(
                                      (String) quadratic(a, b, c, -1)
                                      .match(good -> "x = " + good,
                                      bad -> "Oopsie: " + bad));



                                      Conclusion



                                      For your specific example, just use Floating Point. For a more general solution, I find union types more useful than Exceptions. You can use union types as arguments to a method that might take two different inputs which have no common interface or ancestor. They are also more friendly to Functional Programming.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Oct 20 '17 at 1:02

























                                      answered Aug 20 '13 at 23:33









                                      GlenPetersonGlenPeterson

                                      2,04812132




                                      2,04812132





















                                          3














                                          Write a function that returns an Object. Have it either return the Boolean or Integer wrapper objects. Then use instanceof to figure out which to use.






                                          share|improve this answer



























                                            3














                                            Write a function that returns an Object. Have it either return the Boolean or Integer wrapper objects. Then use instanceof to figure out which to use.






                                            share|improve this answer

























                                              3












                                              3








                                              3







                                              Write a function that returns an Object. Have it either return the Boolean or Integer wrapper objects. Then use instanceof to figure out which to use.






                                              share|improve this answer













                                              Write a function that returns an Object. Have it either return the Boolean or Integer wrapper objects. Then use instanceof to figure out which to use.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Feb 10 '11 at 2:48









                                              Alex ChurchillAlex Churchill

                                              3,19732341




                                              3,19732341





















                                                  1














                                                  No, one return reference to a customer.



                                                  You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.



                                                  But if I was a user I'd think your design was confusing.






                                                  share|improve this answer



























                                                    1














                                                    No, one return reference to a customer.



                                                    You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.



                                                    But if I was a user I'd think your design was confusing.






                                                    share|improve this answer

























                                                      1












                                                      1








                                                      1







                                                      No, one return reference to a customer.



                                                      You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.



                                                      But if I was a user I'd think your design was confusing.






                                                      share|improve this answer













                                                      No, one return reference to a customer.



                                                      You can write a response object that encapsulates a boolean and an int together and set the values according to your whim.



                                                      But if I was a user I'd think your design was confusing.







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Feb 10 '11 at 2:46









                                                      duffymoduffymo

                                                      274k36322511




                                                      274k36322511





















                                                          1














                                                          my teacher had a cool idea for a tryParse C# like method in java hope it helps



                                                          import java.util.Scanner;

                                                          public class Program
                                                          static Scanner scanner = new Scanner(System.in);
                                                          public static void main(String[] args)
                                                          System.out.println("Enter number");
                                                          String input = scanner.next();
                                                          int[] num =0;
                                                          if(tryParse(input,num))
                                                          System.out.println(num[0] * num[0]);

                                                          static boolean tryParse(String inputString,int[] outputInt)
                                                          try
                                                          outputInt[0] = Integer.parseInt(inputString);
                                                          return true;
                                                          catch(Exception e)
                                                          return false;








                                                          share|improve this answer



























                                                            1














                                                            my teacher had a cool idea for a tryParse C# like method in java hope it helps



                                                            import java.util.Scanner;

                                                            public class Program
                                                            static Scanner scanner = new Scanner(System.in);
                                                            public static void main(String[] args)
                                                            System.out.println("Enter number");
                                                            String input = scanner.next();
                                                            int[] num =0;
                                                            if(tryParse(input,num))
                                                            System.out.println(num[0] * num[0]);

                                                            static boolean tryParse(String inputString,int[] outputInt)
                                                            try
                                                            outputInt[0] = Integer.parseInt(inputString);
                                                            return true;
                                                            catch(Exception e)
                                                            return false;








                                                            share|improve this answer

























                                                              1












                                                              1








                                                              1







                                                              my teacher had a cool idea for a tryParse C# like method in java hope it helps



                                                              import java.util.Scanner;

                                                              public class Program
                                                              static Scanner scanner = new Scanner(System.in);
                                                              public static void main(String[] args)
                                                              System.out.println("Enter number");
                                                              String input = scanner.next();
                                                              int[] num =0;
                                                              if(tryParse(input,num))
                                                              System.out.println(num[0] * num[0]);

                                                              static boolean tryParse(String inputString,int[] outputInt)
                                                              try
                                                              outputInt[0] = Integer.parseInt(inputString);
                                                              return true;
                                                              catch(Exception e)
                                                              return false;








                                                              share|improve this answer













                                                              my teacher had a cool idea for a tryParse C# like method in java hope it helps



                                                              import java.util.Scanner;

                                                              public class Program
                                                              static Scanner scanner = new Scanner(System.in);
                                                              public static void main(String[] args)
                                                              System.out.println("Enter number");
                                                              String input = scanner.next();
                                                              int[] num =0;
                                                              if(tryParse(input,num))
                                                              System.out.println(num[0] * num[0]);

                                                              static boolean tryParse(String inputString,int[] outputInt)
                                                              try
                                                              outputInt[0] = Integer.parseInt(inputString);
                                                              return true;
                                                              catch(Exception e)
                                                              return false;









                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Jan 5 '12 at 19:17









                                                              MunchyzzzMunchyzzz

                                                              111




                                                              111





















                                                                  0














                                                                  This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.






                                                                  share|improve this answer



























                                                                    0














                                                                    This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.






                                                                    share|improve this answer

























                                                                      0












                                                                      0








                                                                      0







                                                                      This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.






                                                                      share|improve this answer













                                                                      This may not be the best solution depending on what you want to do, but an easy way to solve the problem might be to have the function return an int or a constant outside the possible range (such as RETURNED_FALSE/TRUE) and check for that.







                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Feb 10 '11 at 2:56









                                                                      EscapeNTEscapeNT

                                                                      224




                                                                      224





















                                                                          -1














                                                                          I would say it is possible. But not directly.



                                                                          I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.



                                                                          Add your values to a Map like below. And get it with its key!



                                                                          public static HashMap returnAnyType()
                                                                          String x = "This";
                                                                          int a = 9;

                                                                          HashMap<String, Object> myMap = new HashMap();
                                                                          myMap.put("stringVal", x);
                                                                          myMap.put("intVal", a);
                                                                          return myMap;


                                                                          String theStringFromTheMap = (String) returnAnyType().get("stringVal");
                                                                          int theIntFromTheMap = (Integer) returnAnyType().get("intVal");

                                                                          System.out.println("String : " + theStringFromTheMap + " is great !");
                                                                          System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));



                                                                          Output (both are returned from same method):




                                                                          String : This is great!
                                                                          Integer: 19



                                                                          Note:

                                                                          This is not a good practice. But it helps sometimes when it is needed!






                                                                          share|improve this answer

























                                                                          • Why down voted ? Please explain !

                                                                            – smilyface
                                                                            Dec 30 '15 at 9:35











                                                                          • I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                            – Solomon Ucko
                                                                            Dec 22 '16 at 1:10












                                                                          • stackoverflow.com/a/19044187/2086966 Please go through

                                                                            – smilyface
                                                                            Mar 24 at 7:29















                                                                          -1














                                                                          I would say it is possible. But not directly.



                                                                          I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.



                                                                          Add your values to a Map like below. And get it with its key!



                                                                          public static HashMap returnAnyType()
                                                                          String x = "This";
                                                                          int a = 9;

                                                                          HashMap<String, Object> myMap = new HashMap();
                                                                          myMap.put("stringVal", x);
                                                                          myMap.put("intVal", a);
                                                                          return myMap;


                                                                          String theStringFromTheMap = (String) returnAnyType().get("stringVal");
                                                                          int theIntFromTheMap = (Integer) returnAnyType().get("intVal");

                                                                          System.out.println("String : " + theStringFromTheMap + " is great !");
                                                                          System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));



                                                                          Output (both are returned from same method):




                                                                          String : This is great!
                                                                          Integer: 19



                                                                          Note:

                                                                          This is not a good practice. But it helps sometimes when it is needed!






                                                                          share|improve this answer

























                                                                          • Why down voted ? Please explain !

                                                                            – smilyface
                                                                            Dec 30 '15 at 9:35











                                                                          • I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                            – Solomon Ucko
                                                                            Dec 22 '16 at 1:10












                                                                          • stackoverflow.com/a/19044187/2086966 Please go through

                                                                            – smilyface
                                                                            Mar 24 at 7:29













                                                                          -1












                                                                          -1








                                                                          -1







                                                                          I would say it is possible. But not directly.



                                                                          I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.



                                                                          Add your values to a Map like below. And get it with its key!



                                                                          public static HashMap returnAnyType()
                                                                          String x = "This";
                                                                          int a = 9;

                                                                          HashMap<String, Object> myMap = new HashMap();
                                                                          myMap.put("stringVal", x);
                                                                          myMap.put("intVal", a);
                                                                          return myMap;


                                                                          String theStringFromTheMap = (String) returnAnyType().get("stringVal");
                                                                          int theIntFromTheMap = (Integer) returnAnyType().get("intVal");

                                                                          System.out.println("String : " + theStringFromTheMap + " is great !");
                                                                          System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));



                                                                          Output (both are returned from same method):




                                                                          String : This is great!
                                                                          Integer: 19



                                                                          Note:

                                                                          This is not a good practice. But it helps sometimes when it is needed!






                                                                          share|improve this answer















                                                                          I would say it is possible. But not directly.



                                                                          I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.



                                                                          Add your values to a Map like below. And get it with its key!



                                                                          public static HashMap returnAnyType()
                                                                          String x = "This";
                                                                          int a = 9;

                                                                          HashMap<String, Object> myMap = new HashMap();
                                                                          myMap.put("stringVal", x);
                                                                          myMap.put("intVal", a);
                                                                          return myMap;


                                                                          String theStringFromTheMap = (String) returnAnyType().get("stringVal");
                                                                          int theIntFromTheMap = (Integer) returnAnyType().get("intVal");

                                                                          System.out.println("String : " + theStringFromTheMap + " is great !");
                                                                          System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));



                                                                          Output (both are returned from same method):




                                                                          String : This is great!
                                                                          Integer: 19



                                                                          Note:

                                                                          This is not a good practice. But it helps sometimes when it is needed!







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Mar 24 at 7:24

























                                                                          answered Dec 30 '15 at 8:48









                                                                          smilyfacesmilyface

                                                                          1,80832240




                                                                          1,80832240












                                                                          • Why down voted ? Please explain !

                                                                            – smilyface
                                                                            Dec 30 '15 at 9:35











                                                                          • I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                            – Solomon Ucko
                                                                            Dec 22 '16 at 1:10












                                                                          • stackoverflow.com/a/19044187/2086966 Please go through

                                                                            – smilyface
                                                                            Mar 24 at 7:29

















                                                                          • Why down voted ? Please explain !

                                                                            – smilyface
                                                                            Dec 30 '15 at 9:35











                                                                          • I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                            – Solomon Ucko
                                                                            Dec 22 '16 at 1:10












                                                                          • stackoverflow.com/a/19044187/2086966 Please go through

                                                                            – smilyface
                                                                            Mar 24 at 7:29
















                                                                          Why down voted ? Please explain !

                                                                          – smilyface
                                                                          Dec 30 '15 at 9:35





                                                                          Why down voted ? Please explain !

                                                                          – smilyface
                                                                          Dec 30 '15 at 9:35













                                                                          I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                          – Solomon Ucko
                                                                          Dec 22 '16 at 1:10






                                                                          I didn't downvote, but I do have a few questions/comments: 1. You should specify type parameters for the HashMap. 2. How do you make the keys?

                                                                          – Solomon Ucko
                                                                          Dec 22 '16 at 1:10














                                                                          stackoverflow.com/a/19044187/2086966 Please go through

                                                                          – smilyface
                                                                          Mar 24 at 7:29





                                                                          stackoverflow.com/a/19044187/2086966 Please go through

                                                                          – smilyface
                                                                          Mar 24 at 7:29











                                                                          -2














                                                                          inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.






                                                                          share|improve this answer



























                                                                            -2














                                                                            inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.






                                                                            share|improve this answer

























                                                                              -2












                                                                              -2








                                                                              -2







                                                                              inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.






                                                                              share|improve this answer













                                                                              inout parameters only work for objects that can be mutated. For String inout parameters, pass in StringBuilders instead of Strings, then replace() their values.







                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Apr 25 '12 at 17:41









                                                                              Jeff CaswellJeff Caswell

                                                                              1




                                                                              1



























                                                                                  draft saved

                                                                                  draft discarded
















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid


                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function ()
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4952856%2fhow-to-write-java-function-that-returns-values-of-multiple-data-types%23new-answer', 'question_page');

                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                                                                  SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                                                  은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현