Java String to int

Java string to int example using Integer.parseInt()

The Integer.parseInt() method is used to convert string to int in Java. It returns a primitive int value. It throws a NumberFormatException when all the characters in the String are not digits.

Note: The first character in the string can be a minus ‘-‘ sign.

Example:

package com.w3schools;

public class StringToInt {
  public static void main(String args[]){
      String str="231";
      int num1 = 452;
      
      //convert string to int
      int num2 = Integer.parseInt(str);
      int sum=num1+num2;
      System.out.println("Result is: "+sum);
  }
}

Output:

Result is: 683

 

Java string to int example using Integer.valueOf()

The Integer.valueOf() method is used to convert string to int in Java. It returns an object of the Integer class. It throws a NumberFormatException when all the characters in the String are not digits.

Note: The first character in the string can be a minus ‘-‘ sign.

Example:

package com.w3schools;

public class StringToInt {
  public static void main(String args[]){
      String str="-430";
      int num1 = 210;

      //convert string to int
      int num2 = Integer.valueOf(str);
      int sum=num1+num2;
      System.out.println("Result is: "+sum);
  }
}

Output:

Result is: -220

 

Please follow and like us:
Content Protection by DMCA.com