CodesJava

Easy learning with example program codes

String to int in java


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

Please follow and like us:
Posted in Java   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki