1. Methods to convert String to Integer in java
- Given an String in java, we would like convert String to integer.
- Input String strNumber = “9999”
- The output of program should be iNumber = 9999
- We can convert String to integer using following methods.
- Convert String to integer using Integer.parseInt.
- Convert String to integer using Integer.valueOf.
- Convert String to integer using Integer constructor.
2. Program – convert String to Integer in java (example)
package org.learn;
public class ConvertStringToInt {
public static void main(String[] args) {
String strNumber = "9999";
//Method 1
int iNumber = Integer.parseInt(strNumber);
System.out.printf("1. Convert string to integer using Integer.parseInt: %d",iNumber);
//Method 2
iNumber = Integer.valueOf(strNumber);
System.out.printf("\n2. Convert string to integer using Integer.valueOf: %d",iNumber);
//Method 3
iNumber = new Integer(strNumber).intValue();
System.out.printf("\n3. Convert string to integer using Integer constructor: %d",iNumber);
}
}
3. Output – Convert String to Integer in java (with example)
1. Convert string to integer using Integer.parseInt: 9999
2. Convert string to integer using Integer.valueOf: 9999
3. Convert string to integer using Integer constructor: 9999