 # Java program to convert decimal to binary with explanation

Hello Friends! Welcome to Programming Shortcut,
Today we’ll discuss how to convert a decimal to binary in java. there are two methods to convert decimal to binary

## Decimal to binary in java

import java.util.Scanner;
public class DecimaltoBinary  {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int a[] = new int;
System.out.println(“Enter a Decimal number to convert binary”);
int decimalnum = in.nextInt();
int temp = decimalnum; //the taken number to save take temp variable.
int n = 0;
while (temp > 0) { // checking the number to till ‘0’
int rem = temp % 2; // taking remainder of number
temp = temp / 2; // after taking remainder update the number
a[n] = rem;  // store the remainder into a array
n++;
}

//print the array in reverse order
System.out.print(“The binary of ” + decimalnum + ” is: “);
for (int i = n – 1; i >= 0; i–) {
System.out.print(a[i]);
}
System.out.println(“n”);
}
}

Output:
Enter a Decimal number to convert binary
23
The binary of 23 is: 10111

## Decimal to binary in java without array

import java.util.Scanner;
public class DecimaltoBinary  {    public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.println(“Enter a Decimal number to convert binary”);
int num = input.nextInt();
int n = num;
String temp = “”;
while (n > 0) {
int rem = n % 2;
n = n / 2;
temp = temp + rem;
}
String bin = new StringBuffer(temp).reverse().toString();

System.out.println(“The binary number of ” + num + ” is: ” + bin);
}
}

Output:
Enter a Decimal number to convert binary
24
The binary number of 24 is: 11000

I make this programming and hope you are like the post if are you like the post you can please comment and Share the post to reach more people.