Java Long toBinaryString() Method

Java toBinaryString() method is the part of the Long class of the java.lang package. This method is used to return the binary equivalent of base 2 of the value passed as an unsigned long as a String.

For example: for the value 54, the equivalent binary string returned will be 110110.

Syntax:

public static String toBinaryString (long i)  

Parameters:

The parameter passed is the long value of which the string representation of the equivalent binary of base 2 is to be returned.

Returns:

Returns the String representation of the parameter passed as equivalent base 2 binary value.

Example 1:

Here, a positive and a negative number is taken for a better understanding of the method.

import java.lang.Long;

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        long i = 121L; 
        long j = -53L;
        System.out.println("Actual number is = " + i);  
        System.out.println("Binary equivalent is = " + Long.toBinaryString(i)); //returns the long value in binary base 2 as a string
        
        System.out.println("Actual number is = " + j);  
        System.out.println("Binary equivalent is = " + Long.toBinaryString(j)); //returns the long value in binary base 2 as a string        
    }  
}


Actual number is = 121
Binary equivalent is = 1111001
Actual number is = -53
Binary equivalent is = 1111111111111111111111111111111111111111111111111111111111001011

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  

public class StudyTonight
{  
	public static void main(String[] args) 
	{  
		try
		{
			System.out.print("Enter the Number = ");  
			Scanner sc = new Scanner(System.in);  
			long i = sc.nextLong();  
			System.out.println("Actual Number is  = " + i);  
			System.out.println("Binary representation is = " + Long.toBinaryString(i)); //returns the long value in binary base 2 as a string 
		}  
		catch(Exception e)
		{
			System.out.println("Invalid Number");
		}
	}
}  


Enter the Number = 755
Actual Number is = 755
Binary representation is = 1011110011
**********************************************
Enter the Number = -677
Actual Number is = -677
Binary representation is = 1111111111111111111111111111111111111111111111111111110101011011
********************************************
Enter the Number = 0x577
Invalid Number

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.