Search code examples
javaserializationintegerautoboxingunboxing

Why is Integer.parseInt(String str) returns int instead of Integer in Java?


I am asking this question because I have to a situation where I have the following two methods:

public T get(Serializable id) and
public T get(int id) 

I have to use the first method in most scenarios and the second method is already deprecated in our system.

My inputs are String so every time I need to call the get(Serializable id) , I have to pass Integer instead of int, otherwise it will use the second method which is deprecated. i.e I have to call Integer.parseInt(str) and then I have to Box it to Integer ( i.e (Integer)Integer.parseInt(str)) which seems redundant.

Is there a better way to do this and why is the implementation of Integer.parseInt(str) return int instead of Integer?


Solution

  • why is the implementation of Integer.parseInt(str) return int instead of Integer?

    Because Integer.parseInt was designed to return int and that is its return type.

    Is there a better way to do this...

    If you want to get Integer instead of int use Integer.valueOf.