Quick Reach
String to int conversion
In programming the most used data is of int (as for as numbers are concerned) and strings (if you are working with text) in any programming language. So scenarios come when you need to convert one data type into other to fulfill a task. This tutorial explains how to convert a java string to int.
An example of string to int by valueof
example by parseInt method
Using valueof method of integer to convert java string to integer
The Integer’s method valueof can be used to convert a string to int in java. The general syntax of using java valueof method is:
Integer.valueof (string). intValue;
e.g.
a = Integer.valueof(s).intValue;
where a is an int type and s is a string.
String to int example by valueof method of Integer
The example below first shows what happens if a string variable stra = “45” is used in addition i.e. c = a + stra. As such stra is a string it will generate an error as follows:
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class conversion_example {
public static void main(String []args) {
int a = 50;
int c;
String stra = "45";
c = a + stra;
System.out.println(c);
}
}
|
The output will be:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from String to int
at test_package.conversion_example.main(conversion_example.java:8)
As you can see it generated String to int java error.
Now let us show you how to convert that java string to int and then adding two variables…
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class conversion_example {
public static void main(String []args) {
int a = 50;
int c;
String strb = "45";
c = a + Integer.valueOf(strb).intValue();;
System.out.println(c);
}
}
|
The output will be:
95
Using parseInt method to convert string to int
You can also use java parseInt method of Integer to convert a string to int. The syntax is:
static int parseInt(String);
Convert string to int by parseInt method of Integer
The example below converts a string to int java by using parseInt and then used in adding two int variables.
Experience this online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class conversion_example {
public static void main(String []args) {
int a = 50;
int c;
String strb = "45";
c = a + Integer.parseInt(strb);
System.out.println(c);
}
}
|
The output will be:
95
Also see: java int to string
Leave A Comment?