Java Program to Convert Decimal to Binary
Integer.toBinaryString(decimalNumber) or by repeatedly dividing the number by 2 and collecting remainders.Examples
How to Think About It
Algorithm
Code
public class DecimalToBinary { public static void main(String[] args) { int decimal = 10; String binary = Integer.toBinaryString(decimal); System.out.println("Binary of " + decimal + " is: " + binary); } }
Dry Run
Let's trace converting decimal 5 to binary using repeated division.
Divide 5 by 2
5 / 2 = 2 remainder 1
Divide 2 by 2
2 / 2 = 1 remainder 0
Divide 1 by 2
1 / 2 = 0 remainder 1
| Quotient | Remainder |
|---|---|
| 5 | 1 |
| 2 | 0 |
| 1 | 1 |
Why This Works
Step 1: Using Integer.toBinaryString
Java's Integer.toBinaryString method converts the decimal number directly to its binary string representation.
Step 2: Manual division method
Dividing the decimal number by 2 repeatedly and collecting remainders builds the binary digits from least significant to most significant.
Step 3: Reversing remainders
Reading the collected remainders in reverse order gives the correct binary number.
Alternative Approaches
public class DecimalToBinaryManual { public static void main(String[] args) { int decimal = 10; StringBuilder binary = new StringBuilder(); int num = decimal; if (num == 0) { binary.append('0'); } while (num > 0) { binary.append(num % 2); num /= 2; } System.out.println("Binary of " + decimal + " is: " + binary.reverse().toString()); } }
import java.util.stream.Collectors; import java.util.stream.IntStream; public class DecimalToBinaryStream { public static void main(String[] args) { int decimal = 10; String binary = IntStream.iterate(decimal, n -> n > 0, n -> n / 2) .map(n -> n % 2) .mapToObj(String::valueOf) .collect(Collectors.collectingAndThen(Collectors.toList(), lst -> { java.util.Collections.reverse(lst); return String.join("", lst); })); System.out.println("Binary of " + decimal + " is: " + binary); } }
Complexity: O(log n) time, O(log n) space
Time Complexity
The conversion requires dividing the number by 2 repeatedly until it reaches 0, which takes about log base 2 of n steps.
Space Complexity
Storing the binary digits requires space proportional to the number of bits, which is also about log base 2 of n.
Which Approach is Fastest?
Using Integer.toBinaryString is fastest and most efficient, while manual methods are educational but slower and more error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Integer.toBinaryString | O(log n) | O(log n) | Quick and simple conversion |
| Manual division with StringBuilder | O(log n) | O(log n) | Learning and understanding process |
| Java Streams method | O(log n) | O(log n) | Functional programming style |
Integer.toBinaryString() for quick and easy decimal to binary conversion in Java.