The parseInt() method is used to convert the string to an integer as a parameter. That is:
Integer.parseInt(string_varaible)
Let us see what will happened while we add a string value and an integer without any sort of conversion:
class Test {
public static void main(String[] args) {
String age = "30";
System.out.println(age + 30);
// 3030
}
}
In the above example, we created an age variable with a string value of "30".
While added to an integer value of 30, we got 3030 instead of 60.
Here's a solution using the parseInt() method:
class Test {
public static void main(String[] args) {
String age = "30";
int age_to_int = Integer.parseInt(age);
System.out.println(age_to_int + 30);
// 60
}
}
In order to convert the age variable to an integer, we passed it as a parameter to the parseInt() method — Integer.parseInt(age) — and stored it in a variable called age_to_int.
When added to another integer, we got a proper addition: age_to_int + 30.
Comments (0)