java.lang.Integer toBinaryString()

Description :

This java tutorial shows how to use the toBinaryString() method of Integer class under java.lang package. This method return a string equivalent in binary base number of the int method argument.

Method Syntax :

public static String toBinaryString(int i)

Parameter Input :

DataType Parameter Description
int i the integer value that we want to convert into string in binary base number

Method Returns :

The toBinaryString(int i) method simply returns the binary string equivalent of int method parameter.

Compatibility Version :

Requires Java 1.0.2 and up

Exception :


Discussion :

The toBinaryString() method is static thus we should invoke it statically for example Integer.toBinaryString(int i). This method simply converts the int parameter into binary or we could call it base 2. Make a note that counting numbers are of base 10. Binary numbers consist of 1 and 0 digit only.

The toBinaryString() method would yield the same result in invoking Integer.toString(int i, int radix). This is just only a shortcut of calling the toString(int i,2). You might be asking when to use this method. Well, to answer this kind of concern, if you are only dealing with fix base 2, it would make sense to use the toBinaryString() because it is simpler to look at. But if you are dealing with dynamic conversion then the toString(int i, int radix) method suits better.

There is maximum and minimum allowable value to be converted and this is can be determined using the two static method Integer.MAX_VALUE and Integer.MIN_VALUE respectively.

Java Code Example :

This java example source code demonstrates the use of toBinaryString() method of Scanner class. Basically we will be getting a number from user console input and convert the same into binary format.


import java.util.Scanner;

import static java.lang.System.*;

 * This example source code demonstrates the use of toBinaryString
 * of Integer class

public class IntegerToBinaryString {

	public static void main(String[] args) {
		// Ask user input
		// declare the scanner object
		Scanner scan = new Scanner(;
		// use scanner to get the value from user console
		int value = scan.nextInt();
		// close the scanner object
		// print the value in binary format
		out.println("Number in binary base number:" + Integer.toBinaryString(value));



Sample Output :

Running the toBinaryString() method example source code of Integer class will give you the following output

Number in binary base number:10100101001

Exception Scenario :

Exception in thread "main" java.util.InputMismatchException: For input string: "2147483648"
	at java.util.Scanner.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)

Similar Method :

  • N/A

Suggested Reading List :

References :