Java Convert String to int - How to Convert String to int in java?

Overview

In this tutorial, we show you how to convert String to Int in java. 3 ways to convert String we can use the Integer.parseInt() method or the Integer.valueOf() method to convert String into Integer object. Alternatively, we can use org.apache.commons.lang.math.NumberUtils.toInt() method in commons-lang-2.6.jar lib.

Java Convert String to int

Using java.lang.Integer.parseInt()

String str = "1";
int numberFormated = Integer.parseInt(str);
System.out.println("numberFormated: " + numberFormated);

Using java.lang.Integer.valueOf()

The Integer.valueOf() method converts String into Integer object.
String str = "1";
Integer number = = Integer.valueOf(str);
System.out.println("numberFormated: " + number);

Using org.apache.commons.lang.math.NumberUtils.toInt()

  • Download apache-lang common from apache home page
  • To add the commons-lang-2.6.jar to Eclipse Project Library by right click on the Project, select Build Path -> Configure Build Path ... On tab to Libraries -> Add JARs... We use NumberUtils.toInt() method to convert String to int.
String str = "1";
int numberFormated = NumberUtils.toInt(str);
System.out.println("numberFormated: " + numberFormated);
ConvertStringToIntExample.java file example
package com.jackrutorial;

import org.apache.commons.lang.math.NumberUtils;

public class ConvertStringToIntExample {

 public static void main(String[] args) {
  String str = "1";
  System.out.println("String: \"1\"");
  
  //Integer.parseInt()
  int numberFormated = Integer.parseInt(str);
  System.out.println("numberFormated: " + numberFormated);
  
  //Integer.valueOf()
  Integer number = Integer.valueOf(str);
  System.out.println("numberFormated: " + number);
  
  //NumberUtils.toInt()
  numberFormated = NumberUtils.toInt(str);
  System.out.println("numberFormated: " + numberFormated);
 }
}
Previous Post
Next Post

post written by: