Another Approach for Converting a String to Integer
Apart from parseInt() Method in Java there is another method for conversion of String to Integer. Below is the implementation of valueOf() method that is
valueOf() Method
The Integer.valueOf() method converts a String into an Integer object. Let us understand this by an example.
Below is the implementation of the above method:
Java
// Java Program to Demonstrate // Working of valueOf() Method // Main class public class GFG { // Main driver method public static void main(String args[]) { // Custom wide-varied inputs to illustrate // usage of valueOf() method int decimalExample = Integer.valueOf( "20" ); int signedPositiveExample = Integer.valueOf( "+20" ); int signedNegativeExample = Integer.valueOf( "-20" ); int radixExample = Integer.valueOf( "20" , 16 ); int stringExample = Integer.valueOf( "geeks" , 29 ); // Print statements System.out.println(decimalExample); System.out.println(signedPositiveExample); System.out.println(signedNegativeExample); System.out.println(radixExample); System.out.println(stringExample); } } |
20 20 -20 32 11670324
String to int in Java
In Java, while operating upon strings, there are times when we need to convert a number represented as a string into an integer type. We usually do this because we can operate with a wide flexible set of operations over strings. The method generally used to convert String to Integer in Java is parseInt() of the String class.
In this article, we will see how to convert a String to int in Java.