Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversions of strings to Integer and to int

Given that String s has been declared, the following 5 lines of code produce the same result:

int i = Integer.valueOf(s);
int y = Integer.parseInt(s);
int j = Integer.valueOf(s).intValue();
Integer x = Integer.valueOf(s);
Integer k = Integer.valueOf(s).intValue();

Are there circumstances where each one would be the preferred code? It appears that int and Integer are interchangeable and that .intValue() is not needed.

like image 619
Nick Avatar asked Dec 26 '22 10:12

Nick


1 Answers

If you require an int, use parseInt(), if you require an Integer use valueOf(). Although they're (sort of) interchangeable now, it still makes more sense to use the one that directly returns the data type that you require. (Historically, they weren't interchangeable at all, this was introduced with auto-boxing and unboxing in Java 5.)

The intValue() method you're using is just converting the Integer class type to the int primitive, so using that and valueOf() is the worst possible combination, you never want to use that. (Nothing bad will happen, it's just longer to read, performs slightly worse and is generally more superfluous.)

If you don't care or don't know, then I'd use parseInt(). Especially as a beginner, it's more common that you want the primitive type rather than the class type.

like image 156
Michael Berry Avatar answered Jan 09 '23 16:01

Michael Berry