Java parseInt() Method Tutorial

Java programming language provides the parseInt() method in order to convert a string into an integer. The provided string should contain numbers in order to convert them into integers properly.

parseInt() Method Syntax

The parseInt() method has the following syntax where a string and radix are accepted. The radix parameter is optional.

static int parseInt(String S,int RADIX)
  • S is the string which will be converted into integer. The S parameter is required.
  • RADIX is optional parameter which is used to specify the decimal, hexadecimal base for the conversion.

Convert String To Integer

In the following example, we will convert different strings into integers by using the Integer.parseInt() method.

public class Test { 

   public static void main(String args[]) {

      int a =Integer.parseInt("9");


      int b =Integer.parseInt("99");

      int c =Integer.parseInt("999");



      System.out.println(a);
      System.out.println(b);
      System.out.println(c);


   }
}

Convert Hexadecimal String to Integer

The parseInt() method can be also used to convert hexadecimal string representation into an integer. In the following example, we convert different hexadecimal string representations into integers. The radix parameter should be provided as 16 to the parseInt() method.

public class Test { 

   public static void main(String args[]) {

      int a =Integer.parseInt("9",16);

      int b =Integer.parseInt("aa",16);

      int c =Integer.parseInt("abc",16);

      System.out.println(a);
      System.out.println(b);
      System.out.println(c);

   }
}

Convert Binary String to Integer

The radix can be also used to convert binary string representation into an integer. The radix parameter is provided as 2 into the parseInt() method.

public class Test { 

   public static void main(String args[]) {

      int a =Integer.parseInt("1",2);

      int b =Integer.parseInt("10101",2);

      int c =Integer.parseInt("1010111101",2);

      System.out.println(a);
      System.out.println(b);
      System.out.println(c);

   }
}

Leave a Comment