Showing posts with the label String to an int

How to convert a String to an int in Java

In this section, we will show you how to convert a String to an int in Java.  Input : str = "3456"  Output : 3456 Input : str = "a3456e"  Output : 0 Input : str = "-3456"  Output : 3456 Following ways can be used for converting String to int: 1. By using Integer.parseInt() method 2. By using  NumberUtils.toInt method of Apache Commons library 3. By using  Ints::tryParse method of Guava library Example 1: Use Integer.parseInt() method Integer.parseInt() method parses the String argument as a signed decimal integer object. The characters in the string must be decimal digits, except that the first character of the string may be an ASCII minus sign '-' to indicate a negative value or an ASCII plus '+' sign to indicate a positive value. It returns the integer value which is represented by the argument in a decimal integer. public class Main { // Driver code public static void main ( String [] args) { //Example 1 S