How to Convert String to int in Java

To convert String to int in Java you can use one of the following options-

  1. Integer.parseInt(String str) method which returns the passed String as int.
  2. Integer.valueOf(String str) method which returns the passed String as Integer.

Java example to convert String to int using Integer.parseInt()

Output

Java example to convert String to int using Integer.valueOf

Output

In this example you can see that valueOf() method returns Integer object, because of autoboxing it can directly be used as int value though.

NumberFormatException

In the examples you can see a try-catch block which catches NumberFormatException which is thrown if an invalid number string is passed for converting to int.
Java example

Output

That’s all for the topic How to Convert String to int in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.