Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Method that returns either String or int

A part of a small program I am coding:

String maxs = "";
int maxi = 0;

At this part I defined two variables as int and String.

public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?

like image 731
Subhi Samara Avatar asked Nov 15 '25 12:11

Subhi Samara


1 Answers

Use Object instead of TypeOfReturn You can change the TypeoOfReturn to Object and then return the respective types.

like image 115
Syed Faisal Abbas Avatar answered Nov 18 '25 06:11

Syed Faisal Abbas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!