Decimal to Binary Conversion in Java — Definition, Examples and Program
Binary numbers are numbers represented in base 2, using only 0s and 1s. Converting a decimal number (base 10) to binary (base 2) is a common operation in programming and computer science.
How to Convert Decimal to Binary?
- Divide the decimal number by 2.
- Write down the remainder.
- Update the number as the quotient from the division.
- Repeat steps 1–3 until the quotient becomes 0.
- The binary representation is the remainders read in reverse order.
Example 1
Decimal Number: 13
- 13 ÷ 2 = 6 remainder 1
- 6 ÷ 2 = 3 remainder 0
- 3 ÷ 2 = 1 remainder 1
- 1 ÷ 2 = 0 remainder 1
Binary: 1101
Example 2
Decimal Number: 25
- 25 ÷ 2 = 12 remainder 1
- 12 ÷ 2 = 6 remainder 0
- 6 ÷ 2 = 3 remainder 0
- 3 ÷ 2 = 1 remainder 1
- 1 ÷ 2 = 0 remainder 1
Binary: 11001
Java Program for Decimal to Binary Conversion
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = sc.nextInt();
int num = decimal;
String binary = "";
while (num > 0) {
int remainder = num % 2;
binary = remainder + binary; // Prepend remainder
num /= 2;
}
System.out.println("Binary of " + decimal + " is " + binary);
}
}
Sample Output
Enter a decimal number: 13
Binary of 13 is 1101
Enter a decimal number: 25
Binary of 25 is 11001
Practice Challenges
- Write a program to convert decimal to binary without using strings (using array or bitwise operations).
- Modify the program to convert multiple decimal numbers entered by the user into binary.
- Write a program to convert decimal to octal and hexadecimal using similar logic.
Decimal to binary conversion is fundamental in computer science, digital electronics, and low-level programming. This Java program helps beginners understand the process step by step.