Java.lang.Integer.parseInt() Method

Advertisements


Description

The java.lang.Integer.parseInt(String s, int radix) method parses the string argument s as a signed integer in the radix specified by the second argument radix.Some examples can be seen here:

 parseInt("0", 10) returns 0
 parseInt("222", 10) returns 222
 parseInt("-0", 10) returns 0
 parseInt("-BB", 16) returns -187
 parseInt("1010110", 2) returns 86
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("ADMIN", 27) returns 5586836

Declaration

Following is the declaration for java.lang.Integer.parseInt() method

public static int parseInt(String s, int radix) throws NumberFormatException

Parameters

  • s -- This is a String containing the integer representation to be parsed.

  • radix -- This is the radix to be used while parsing s.

Return Value

This method returns the integer represented by the string argument in the specified radix.

Exception

  • NumberFormatException -- if the string does not contain a parsable int.

Example

The following example shows the usage of java.lang.Integer.parseInt() method.

package com.tutorialspoint;

import java.lang.*;

public class IntegerDemo {

   public static void main(String[] args) {

     // parses the string with specified radix
     int a = Integer.parseInt("0", 10);
     System.out.println(a);
 
     int b = Integer.parseInt("222", 10);
     System.out.println(b);
  
     int c = Integer.parseInt("-0", 10);
     System.out.println(c);
   
     int d = Integer.parseInt("-BB", 16);
     System.out.println(d);
   
     int e = Integer.parseInt("1010110", 2);
     System.out.println(e);
   
     int f = Integer.parseInt("2147483647", 10);
     System.out.println(f);

     int g = Integer.parseInt("-2147483648", 10);
     System.out.println(g);
   
     int h = Integer.parseInt("ADMIN", 27);
     System.out.println(h);
   }
} 

Let us compile and run the above program, this will produce the following result:

0
222
0
-187
86
2147483647
-2147483648
5586836



Advertisements
Advertisements