September 3, 2022

How to Convert String to int in Java

To convert String to int in Java you can use one of the following options-

  1. Integer.parseInt(String str) method which returns the passed String as int.
  2. Integer.valueOf(String str) method which returns the passed String as Integer.

Java example to convert String to int using Integer.parseInt()

public class StringToInt {
  public static void main(String[] args) {
    String str = "12";
    try{
      int num = Integer.parseInt(str);
      System.out.println("value - " + num);
      // can be used in arithmetic operations now
      System.out.println(num+"/3 = " + num/3);
    }catch(NumberFormatException exp){
      System.out.println("Error in conversion " + exp.getMessage());
    }  
  }
}
Output
value - 12
12/3 = 4

Java example to convert String to int using Integer.valueOf

public class StringToInt {
  public static void main(String[] args) {
    String str = "12";
    try{
      Integer num = Integer.valueOf(str);
      System.out.println("value - " + num);
      // can be used in arithmetic operations now
      System.out.println(num+"/3 = " + num/3);
    }catch(NumberFormatException exp){
      System.out.println("Error in conversion " + exp.getMessage());
    }  
  }
}
Output
value - 12
12/3 = 4

In this example you can see that valueOf() method returns Integer object, because of autoboxing it can directly be used as int value though.

NumberFormatException

In the examples you can see a try-catch block which catches NumberFormatException which is thrown if an invalid number string is passed for converting to int.

public class StringToInt {
  public static void main(String[] args) {
    String str = "123ab";
    try{
      Integer num = Integer.valueOf(str);
      System.out.println("value - " + num);
      // can be used in arithmetic operations now
      System.out.println(num+"/3 = " + num/3);
    }catch(NumberFormatException exp){
      System.out.println("Error in conversion " + exp.getMessage());
      throw exp;
    }  
  }
}
Output
Error in conversion For input string: "123ab"
Exception in thread "main" 
java.lang.NumberFormatException: For input string: "123ab"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.valueOf(Unknown Source)
	at com.knpcode.programs.StringToInt.main(StringToInt.java:8)

That's all for the topic How to Convert String to int in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment