Java Online Compiler
Example: Decimal to Binary Converter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Decimal to Binary Converter import java.util.Scanner; // Main class containing the entry point of the program public class Main { // Method to convert a decimal number to its binary representation public static String convertDecimalToBinary(int decimalNumber) { // Handle the special case for 0 if (decimalNumber == 0) { return "0"; } StringBuilder binaryBuilder = new StringBuilder(); // Repeatedly divide the decimal number by 2 // and append the remainder to the StringBuilder while (decimalNumber > 0) { int remainder = decimalNumber % 2; // Get the remainder binaryBuilder.append(remainder); // Append remainder decimalNumber = decimalNumber / 2; // Update decimal number } // The binary string is built in reverse, so reverse it before returning return binaryBuilder.reverse().toString(); } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a decimal number System.out.print("Enter a decimal number: "); // Step 3: Read the integer input from the user int decimal = scanner.nextInt(); // Step 4: Call the conversion method String binaryResult = convertDecimalToBinary(decimal); // Step 5: Print the binary equivalent System.out.println("The binary equivalent is: " + binaryResult); // Step 6: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS