How to convert a string to int in Java

Java has two methods, which deal with converting strings to each of these types. Let’s look at both the methods used for this conversion.

  1. An int data type which is a primitive data type
  2. An Integer class which contains an element of type int

Converting string to int

This uses the method, Integer.parseInt(str). This method takes in one parameter of type String, str, and returns the number in int format.

Using Integer.parseInt()

Example

class stringToint {
public static void main( String args[] ) {
String str = "1000";
int num = Integer.parseInt(str);
System.out.println(num);
}
}

Converting string to integer

This uses the method Integer.valueOf(str) to convert a string to Integer format. In this case, it also takes in a single String str, and changes the value to an Integer.

Using Integer.valueOf()

Example

class stringToInteger {
public static void main( String args[] ) {
String str = "1000";
Integer num = Integer.valueOf(str);
System.out.println(num);
}
}

Note: If the string contains letters along with numbers the function will return an exception in this case, as shown in the code below.

class stringToInteger {
public static void main( String args[] ) {
String str = "100A0";
Integer num = Integer.valueOf(str);
System.out.println(num);
}
}
Copyright ©2024 Educative, Inc. All rights reserved