Example 1: Java Program to Convert string to int using parseInt()
In the above example, we have used the parseInt() method of the Integer class to convert the string variables into the int.
Here, Integer is a wrapper class in Java. To learn more, visit the Java Wrapper Class.
Note: The string variables should represent the int values. Otherwise the compiler will throw an exception. For example,
Example 2: Java Program to Convert string to int using valueOf()
We can also convert the string variables into an object of Integer using the valueOf() method. For example,
In the above example, the valueOf() method of Integer class converts the string variables into the int.
Here, the valueOf() method actually returns an object of the Integer class. However, the object is automatically converted into the primitive type. This is called unboxing in Java. To learn more, visit Java autoboxing and unboxing.
That is,
// valueOf() returns object of Integer
// object is converted onto int
int num1 = Integer obj = Integer.valueOf(str1)