Java Online Compiler
Example: Decimal to Binary Converter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Decimal to Binary Converter in Java import java.util.Scanner; // Main class containing the entry point of the program public class Main { 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: "); int decimalNumber = scanner.nextInt(); // Step 3: Handle the special case for 0 if (decimalNumber == 0) { System.out.println("Binary representation: 0"); scanner.close(); return; } // Step 4: Initialize a StringBuilder to store binary digits StringBuilder binaryResult = new StringBuilder(); // Step 5: Perform repeated division by 2 int tempDecimal = decimalNumber; while (tempDecimal > 0) { int remainder = tempDecimal % 2; // Get the remainder binaryResult.append(remainder); // Append the remainder tempDecimal = tempDecimal / 2; // Divide by 2 } // Step 6: Reverse the StringBuilder to get the correct binary order binaryResult.reverse(); // Step 7: Print the binary representation System.out.println("Binary representation: " + binaryResult.toString()); // Step 8: Close the scanner scanner.close(); } }
13
Output
Clear
ADVERTISEMENTS