1

How return integer in function String

It's my code

public class Utils {
    public static String type(String s){
        if(UraniumProtectMain.materialname){
            return s;
        } else {
            return Integer.parseInt(s); //<--- It's
        }
    }
}
2
  • What are you trying to accomplish with your code? This is not clear right now. Commented Nov 17, 2015 at 6:12
  • 5
    The method in Java can't return either String or int - you should use only one. Commented Nov 17, 2015 at 6:12

3 Answers 3

1

As you want to return both Integer and String, you can use return type as Object class, because Object is super class of all classes and we can hold any type of value in Object variable.

public static Object type(String s){    
    // code here
}

Now you can get the type of value return by type with the help of instanceOf method

if(Utils.type() instaceOf String)
{
    // code here
} else if(Utils.type() instanceOf Integer) {
    // code here
}
Sign up to request clarification or add additional context in comments.

3 Comments

you'd better explain why he has to do that
he want to return both Integer and String this can be accomplished with help of Object class, as you know Object variable can hold any type of value. And he can easily get the type with the help of instanceOf method
great, I wrote that because your answer flagged as a low quality answer, here in SO, you are always required to explain your answer, like what you did in the comment to me but you have to do that in the answer itself to avoid being flagged as a low quality answer.
1

Either return Object or return integer as String.

Comments

0

As User has suggested that you can return change method return type to object. But, apart from that you can also use either of

  1. String.valueOf(number) (my preference)
  2. Integer.toString(number)

to return integer as string and perform type check at method calling point

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.