Decimal to Binary in Java: Explanation & Practice

Convert a decimal number to its binary representation

Problem summary

Write a program that converts a decimal integer to its binary string representation.

Starter code

public class Main {
    public static void main(String[] args) {
        int decimal = 10; // Test case 1
        
        // Convert decimal to binary
        // Print: Binary: <result>
    }
}

Expected output and test cases

  • 10 = 1010
    Binary: 1010
  • 15 = 1111
    Binary: 1111
  • 1 = 1
    Binary: 1

Hints

  1. Divide by 2 and collect remainders
  2. Build string in reverse
  3. Or use Integer.toBinaryString()

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler