How do you convert a String to an Integer in Java?
Given the following String representation of a number
1 | String strNum = "123"; |
Here are two options for the conversion using Integer.parseInt
or Integer.valueOf
Integer.parseInt
1 2 | int num = Integer.parseInt(strNum); System.out.println(num); |
or
Integer.valueOf
1 2 | Integer num = Integer.valueOf(strNum); System.out.println(num); |
Both examples produce the following output to the console:
Console Output
1 | 123 |
Even though both programs print the same result to the console, there is a subtle difference. Notice that the first example returns a primitive int
and the second example produces the Object Integer
.