Convert String to int in Java

Updated on May 12th, 2018

Convert String to int in Java

There are few ways to Convert String to int in Java. Below are few of popular ways for converting String to int

  1. Integer.parseInt()
  2. Integer.valueOf()

1.  Integer.parseInt() Examples

Integer.ParseInt()  will return an int primitive value.If efficiency is your concern and you only need primitive value, then using Integer.ParseInt()  is the best option.

Here is an example to convert “50” to an int value

public class JavaParseInt {
    public static void main(String[] args) {
        String number ="50";
        int result = Integer.parseInt(number);

Here is the output of the above code


2.  Integer.valueOf() Examples

You can also use Integer.valueOf() , this method will return Integer object

public class JavaIntegerValueOf {

    public static void main(String[] args) {
        String number ="60";
        Integer result = Integer.valueOf(number);



Actually, valueOf uses parseInt internally. If efficiency is your concern do not use this method to convert String to int or Integer.

3.  NumberFormat Exception

Both Integer.parseInt()  and Integer.valueOf() can throw NumberFormatException if the string cannot be parsed as an integer or int

public class NumberFormatExceptionExample {

    public static void main(String[] args) {
        String invalidNumber = "abc";


    public static void parseIntNFException(String number) {
        Integer result = Integer.parseInt(number);

    public static void valueOfNFException(String number) {
        Integer result = Integer.valueOf(number);


Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
	at java.lang.NumberFormatException.forInputString(
	at java.lang.Integer.parseInt(
	at java.lang.Integer.parseInt(
	at NumberFormatExceptionExample.parseIntNFException(
	at NumberFormatExceptionExample.main(

Note: PraseInt() return a primitive value while valueOf() will always return new Integer object, ideally, if you just want to convert String to an int, it’s always better to avoid creating new Object.

Furthur Reading

It’s always a good habit to read Javadoc for more inside details

  1. JavaDoc valueOf()
  2. JavaDoc parseInt()
  3. NumberFormatException

Download above examples from

  1. GitHub Repository
0 0 vote
Article Rating

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:
Notify of

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

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
2 years ago

Hi article is nice,
In Java there are two methods to convert String to Int, they are.

Would love your thoughts, please comment.x