There are several ways to convert or parse Java Strings to int values. In Java, Integer values come in various types. We have the primitives long, int, short, and byte; and, we have equivalent Wrapper classes Long, Integer, Short and Byte. But for this post, we’re going to focus on making String to a primitive int value.
Convert or Parse String to Int Using Integer.parseInt
Typically, we use the Integer.parseInt method that only accepts a String value.
1 2 3 4 5 | ... public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); } ... |
For example, consider the following Java codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ... public static void main(String[] args) { SpringApplication.run(ComTurretaString2integerApplication.class, args); String oneHundredTwentyOne = "2021"; String twoThousandTwenty = "2020"; int intVal2020 = Integer.parseInt(twoThousandTwenty); int intVal2021 = Integer.parseInt(oneHundredTwentyOne); System.out.println(intVal2020); System.out.println(intVal2021); } ... |
The codes generate the following output.
1 2 | 2020 2021 |
What if the String is Not Numeric?
Note that the method Integer.parseInt parses and covert String values. What if the String value is not a valid numeric value? The method will throw a NumberFormatException to indicate that the application was unable to parse and convert a String to primitive int.
For example, the following String values will cause the Integer.parseInt method to throw a NumberFormatException.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // java.lang.NumberFormatException: For input string: "" String emptyString = ""; // java.lang.NumberFormatException: For input string: " " String blankString = " "; // java.lang.NumberFormatException: For input string: "a2020" String firstAlpha = "a2020"; // java.lang.NumberFormatException: For input string: "20a20" String middleAlpha = "20a20"; // java.lang.NumberFormatException: For input string: "2020a" String lastAlpha = "2020a"; // java.lang.NumberFormatException: For input string: "*2020" String specialChar = "*2020"; |
On the other hand, the following String values works and Integer.parseInt returns the appropriate int values.
1 2 3 | String plusOneHundredTwentyOne = "+2021"; String noPlusOneHundredTwentyOne = "2021"; String negativeOneHundredTwentyOne = "-2021"; |
Convert String Float-point Value To int
Floating-point numbers are numeric values that contain decimal points. For example, 2021.10. What if we have “2021.10”?
Will the Integer.parseInt be able to parse and convert this Java String to int? The answer is NO and the method will throw NumberFormatException.
1 2 | // java.lang.NumberFormatException: For input string: "2021.10" String oneHundredTwentyOnePoint10 = "2021.10"; |
If you really want to make this work, you’d use Double.parseDouble to parse and convert the String to a primitive double. Then, from a double value, down-cast it to int. Consider the following codes.
1 2 3 4 5 | ... String oneHundredTwentyOnePoint10 = "+2021.10"; int intVal2021 = (int) Double.parseDouble(oneHundredTwentyOnePoint10); System.out.println(intVal2021); ... |
The codes will display the following.
1 | 2020 |
For Validation, should we parse and convert String to int?
It depends. But ideally, we shouldn’t. If you look at the Integer.parseInt codes, it checks each character of the String value and performs the computation. So, it performs two operations for each character. The codes would be more performant if we stick with validating the String value’s format without performing some computation. Therefore, the following codes is inefficient.
1 2 3 4 5 6 7 8 9 10 11 12 | ... String myYear = "2020"; try { Integer.parseInt(myYear); } catch(Exception e) { throw e; } // reUse myYear as String ... |
The following code fragment is from Interger.java (JDK14). Lines 613-615, 631-645, and 648-653 checks the String value format.
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 | public static int parseInt(String s, int radix) throws NumberFormatException { /* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */ if (s == null) { throw new NumberFormatException("null"); } if (radix < Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); } if (radix > Character.MAX_RADIX) { throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); } boolean negative = false; int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; if (len > 0) { char firstChar = s.charAt(0); if (firstChar < '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') { throw NumberFormatException.forInputString(s, radix); } if (len == 1) { // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s, radix); } i++; } int multmin = limit / radix; int result = 0; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE int digit = Character.digit(s.charAt(i++), radix); if (digit < 0 || result < multmin) { throw NumberFormatException.forInputString(s, radix); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s, radix); } result -= digit; } return negative ? result : -result; } else { throw NumberFormatException.forInputString(s, radix); } } |
Validate Java String, don’t convert or parse to int
There are several ways to validate String values without parsing or converting them to primitive int values.
1 – Using Java Regular Expressions
We can use Java Regular Expressions to validate the String value format without converting to int. Consider the following codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class TurretaRegExClassDemo { public static void main(String args[]) { String regex = "^[-+]{0,1}[0-9]{1,9}"; // positive test cases, should all print "true" System.out.println("-1".matches(regex)); System.out.println("1".matches(regex)); System.out.println("9".matches(regex)); System.out.println("+12345".matches(regex)); System.out.println("123456789".matches(regex)); // negative test cases, should all print "false" System.out.println("".matches(regex)); System.out.println("foo".matches(regex)); System.out.println("ar155bz".matches(regex)); System.out.println("1vfe".matches(regex)); // A digit below the max value System.out.println("1234567892".matches(regex)); } } |
On line 4, we specify the Regular Expression or own format for valid int values. The codes generate the following output.
1 2 3 4 5 6 7 8 9 10 | true true true true true false false false false false |
2 – Using Apache Commons Lang
To validate a Java String without converting it to primitive int, we could use StringUtils.isNumeric method from Apache Commons Lang. Consider the following codes.
1 2 3 4 5 6 7 | ... if(!StringUtils.isNumeric(stringToPrimitiveInt)) { return false; // Or throw Exception } int useMe = Integer.parseInt(stringToPrimitiveInt); System.out.println(useMe); ... |