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; public class Main { /** * Converts a decimal integer to its binary string equivalent. * @param decimal The decimal number. * @return The binary string representation of the decimal number. */ public static String decimalToBinary(int decimal) { if (decimal == 0) { return "0"; // Special case for 0 } StringBuilder binaryBuilder = new StringBuilder(); // To efficiently build the binary string int tempDecimal = decimal; // Perform repeated division by 2 while (tempDecimal > 0) { int remainder = tempDecimal % 2; // Get the remainder (0 or 1) binaryBuilder.append(remainder); // Append remainder to the builder tempDecimal /= 2; // Divide the number by 2 } // The binary string is built in reverse, so reverse it before returning return binaryBuilder.reverse().toString(); } public static void main(String[] args) { // Example usage int decimal = 13; String binaryResult = decimalToBinary(decimal); System.out.println("Decimal: " + decimal + " -> Binary: " + binaryResult); // Output: 1101 } }
Output
Clear
ADVERTISEMENTS