# JAVA Program to Convert Decimal to Binary

07 Oct 2019 9:45 am || 0

In this tutorial you will learn how to convert decimal to binary in JAVA using custom and toBinaryString() method.

For eg:

Decimal number: 23

Binary number: 10111 Decimal number: 19

Binary number: 10011 ### Using Custom Method

Example:

``````//Java program to get the the binary notation of a decimal number

//Custom Method

//Importing the Scanner Class of Util Package
import java.util.Scanner;

//Main Class of the Program
public class Main
{
//Main Method of the program
public static void main(String[] args) {
//Declaration of variables
int numberModule,decimalNumber;
String binaryNumber = "";
//Creating the object of Scanner Class
Scanner input = new Scanner(System.in);
//Telling user what to enter
System.out.print("Enter a Decimal Number : ");
//Taking input from user
decimalNumber = input.nextInt();
//Loop till number is greater than 0
while(decimalNumber > 0){
//Finding the modulation of the entered number with 2
numberModule = decimalNumber % 2;
//Adding the modulation result in a variable
binaryNumber = numberModule + "" + binaryNumber;
//removing the last digit from entered number
decimalNumber = decimalNumber / 2;
}
//Printing the result
System.out.println("Binary Notation : "+binaryNumber);
}
}
``````

Output:

``````Enter a Decimal Number : 20
Binary Notation : 10100 ``````

### Using toBinaryString() method

Example:

``````//Java program to get the the binary notation of a decimal number

//toBinaryString()

//Importing the Scanner Class of Util Package
import java.util.Scanner;

//Main Class of the Program
public class Main
{
//Main Method of the program
public static void main(String[] args) {
//Declaration of variables
int numberModule,decimalNumber;
//Creating the object of Scanner Class
Scanner input = new Scanner(System.in);
//Telling user what to enter
System.out.print("Enter a Decimal Number : ");
//Taking input from user
decimalNumber = input.nextInt();
//Taking returned value from the toBinaryString Method in a variable
String binaryNumber = Integer.toBinaryString(decimalNumber);
//Printing the result
System.out.println("Binary Notation : "+binaryNumber);
}
}``````

Output:

``````Enter a Decimal Number : 21
Binary Notation : 10101 ``````

Recommended Posts: