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.
int
data type which is a primitive data typeInteger
class which contains an element of type intThis uses the method, Integer.parseInt(str)
. This method takes in one parameter of type String, str
, and returns the number in int format.
class stringToint {public static void main( String args[] ) {String str = "1000";int num = Integer.parseInt(str);System.out.println(num);}}
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.
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);}}