Introduction
In computer science, number systems play a crucial role in understanding how computers process information. The most commonly used number systems are decimal (base 10) and binary (base 2).
This program demonstrates how to convert a decimal number (base 10) to its binary representation (base 2) using the Java programming language.
Objective
The objective of this program is to take a decimal number as input from the user and convert it to binary. This is done by repeatedly dividing the decimal number by 2, recording the remainders, and then reversing the remainders to form the binary representation.
Java Code
public class DecimalToBinary {
public static void main(String[] args) {
// Create an instance of Scanner to read user input
java.util.Scanner scanner = new java.util.Scanner(System.in);
// Prompt the user to enter a decimal number
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();
// Initialize an empty string to store the binary representation
String binary = "";
// Convert the decimal number to binary
while (decimal > 0) {
binary = (decimal % 2) + binary; // Prepend the remainder (binary digit)
decimal = decimal / 2; // Divide the decimal number by 2
}
// Output the binary representation
System.out.println("The binary representation is: " + binary);
// Close the scanner to avoid resource leak
scanner.close();
}
}
Explanation of the Program Structure
The program follows a simple approach to convert a decimal number to binary:
- Input: It prompts the user to enter a decimal number using the
Scanner
class. - Conversion: The program divides the decimal number by 2, appending the remainder (either 0 or 1) to the binary string. This process is repeated until the decimal number is reduced to 0.
- Output: Once the conversion is complete, the program outputs the binary string.
- Scanner Close: The program ensures that the scanner is closed to avoid any resource leaks.
How to Run the Program
To run this program on your system, follow these steps:
- Ensure you have Java Development Kit (JDK) installed on your system. If not, download and install it from the official Java website.
- Create a new Java file with the name
DecimalToBinary.java
and paste the code into the file. - Open a terminal or command prompt and navigate to the directory where the
DecimalToBinary.java
file is located. - Compile the Java program by running the following command:
javac DecimalToBinary.java
- Run the compiled program with the following command:
java DecimalToBinary
- Enter a decimal number when prompted, and the program will display the corresponding binary number.