Java, Software Development

Java String – Convert or Parse to Primitive int

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.

For example, consider the following Java codes.

The codes generate the following output.

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.

On the other hand, the following String values works and Integer.parseInt returns the appropriate int values.

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.

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.

The codes will display the following.

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.

The following code fragment is from (JDK14). Lines 613-615, 631-645, and 648-653 checks the String value format.

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.

On line 4, we specify the Regular Expression or own format for valid int values. The codes generate the following output.

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.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like