Tutorialspoint examples

Learn java tutorial with examples for beginners online

convert string to int java program


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 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.tutorialspointexamples;
 
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

Download this example.

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 Integer class. It throws 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.tutorialspointexamples;
 
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

Download this example.

Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status