Parse String into Integer value in Java
Tags: String Integer Convert Parse
In this Java core tutorial, we learn how to convert a String value into int value in Java application.
Using Integer.parseInt() static method
Following Java example using Integer.parseInt() static method to convert a String value into int value.
ParseStringToIntExample1.java
public class ParseStringToIntExample1 {
public static void main(String[] args) {
int result1 = Integer.parseInt("1234");
int result2 = Integer.parseInt("+5");
int result3 = Integer.parseInt("-5");
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}
1234
5
-5
The following example using Integer.parseInt() with String value in specified radix.
ParseStringToIntExample2.java
public class ParseStringToIntExample2 {
public static void main(String[] args) {
int result1 = Integer.parseInt("123", 10);// radix 10
int result2 = Integer.parseInt("1010", 2);// radix 2
int result3 = Integer.parseInt("FFAA", 16);// radix 16
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}
123
10
65450
The following example to parse a part of String value into int value.
ParseStringToIntExample3.java
public class ParseStringToIntExample3 {
public static void main(String[] args) {
int beginIndex = 2;
int endIndex = 4;
int radix = 10;
int result = Integer.parseInt("3456789", beginIndex, endIndex, radix);
System.out.println(result);
}
}
56
Using Integer.parseUnsignedInt() static method
Java also provides Integer.parseUnsignedInt() static method to parse String as unsigned integer value.
ParseStringToIntExample4.java
public class ParseStringToIntExample4 {
public static void main(String[] args) throws Exception {
int result1 = Integer.parseUnsignedInt("1234");
int result2 = Integer.parseUnsignedInt("+5");
System.out.println(result1);
System.out.println(result2);
}
}
1234
5
ParseStringToIntExample5.java
public class ParseStringToIntExample5 {
public static void main(String[] args) {
int result1 = Integer.parseUnsignedInt("123", 10);
int result2 = Integer.parseUnsignedInt("1010", 2);
int result3 = Integer.parseUnsignedInt("FFAA", 16);
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}
123
10
65450
ParseStringToIntExample6.java
public class ParseStringToIntExample6 {
public static void main(String[] args) {
int beginIndex = 2;
int endIndex = 4;
int radix = 10;
int result = Integer.parseUnsignedInt("3456789", beginIndex, endIndex, radix);
System.out.println(result);
}
}
56
Happy Coding 😊