How to convert a String to an int in Java?

We will learn today, How to convert String to Int in java. This is very popular written test question in Java interviews.

For example, We have a String "12345" and now I want to represent it in integer.

We can do conversion in 4 ways.

1) Integer.parseInt method.
2) Integer.valueOf
3) Integer constructor
4) DecimalFormat class

string to int


1) Integer.parseInt method:

parseInt(String string) method is static method and it is present in Integer class.


public class ParseIntExample
{
    // Java - W3schools
    public static void main(String[] args)
    {
        String s = "12345";
        int i = Integer.parseInt(s);
        System.out.println("i value : "+i);
    }
}

Output:

i value : 12345

Note: If we pass alphabetic in string to the parseInt method then it will throw NumberFormatException.
For example:


String s = "abcd";
int i = Integer.parseInt(s);

2) Integer.valueOf() method:


valueOf(String string) also a static method in Integer class.



package com.adeepdrive.stringtoint;
public class ValueOfExample
{
    // Java - W3schools
    public static void main(String[] args)
    {
        String s2 = "1000";
        Integer i2 = Integer.valueOf(s2);
        System.out.println("i2 value: "+i2);
   }
}

Output:

i2 value: 1000

Note: valueOf method will throw NumberFormatException, if we pass alphabetic in string. Internally it uses caching for integers range -128 to +127.

parseInt(String string) returns primitive int.
valueOf(String string) returns wrapper Integer.


3) Integer constructor:

Integer class has a constructor which takes String as argument.

Integer(String s): Constructs a newly allocated Integer object that represents the int value indicated by the String parameter.


package com.adeepdrive.stringtoint;

public class IntegerConstructorEx
{
    // Java - W3schools
    public static void main(String[] args)
    {
        String s3 = "999";
        Integer i3 = new Integer(s3);
         // convert Wrapper integer to primitive int
        int int3 = i3.intValue();

        System.out.println("int3 value : " + int3);
    }
}

Output:

int3 value : 999

4) DecimalFormat Class:


DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.


package com.adeepdrive.stringtoint;

import java.text.DecimalFormat;
import java.text.ParseException;

public class DecimalFormatExample
{
    // Java - W3schools
    public static void main(String[] args) throws ParseException
    {
        String string = "123456";

        // Passing "0" to the DecimalFormat indicates that it accepts only digits.
        DecimalFormat decimalFormat = new DecimalFormat("0");

        // parsing String to Number
        Number number = decimalFormat.parse(string);
   
        // converting Number to primitive int.
        int i4 = number.intValue();

       System.out.println("i4 value : " + i4);
    }
}

Output:

i4 value : 123456

0 Comments