In this post, we will learn how to use the Guava Ints.tryParse() method in Java, which is used to parse a string as an integer. We will also see the advantages of using it compared to the built-in methods.

1. What is Ints.tryParse() method?

The Ints.tryParse() method is a simple and elegant way to parse strings as integers. It is similar to the Integer.parseInt() method, but instead of throwing an exception, it returns null if the parsing is not successful. Here is an example of using the Ints.tryParse() method on a valid and an invalid string.

Download Code

 
We can also use the Optional.fromNullable() method from Guava to create an Optional object from the result of Ints.tryParse(). Then it can be used with the Optional.or() method to specify some default value instead of null if the string is not a valid representation of an integer.

Download Code

 
Note that the Ints.tryParse() method returns an Integer object instead of a primitive type. Also note that the Ints.tryParse() method will throw a NullPointerException if the string is null.

2. Comparison with Integer.parseInt() method in Java

The Ints.tryParse() method is not the only way to convert a string into an integer in Java. The Integer.parseInt() method is a built-in way to parse a string into an integer, but it throws a NumberFormatException if the string is not valid. For example:

Download Code

 
Guava’s Ints.tryParse() method has several advantages over Integer.parseInt() method in Java, such as:

  • It does not throw NumberFormatExceptions encountering an invalid string. We do not need to use a try-catch block to handle any exceptions, making our code concise and readable.
  • It allows us to specify a default value to return if the parsing fails. As seen above, we can use the Guava’s Optional class to wrap the result of the Ints.tryParse() method and provide a default value if it is null.

 
For more information about this method, we can check out the Guava official documentation or its GitHub repository.