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
- Divide by 2 and collect remainders
- Build string in reverse
- Or use Integer.toBinaryString()
Related Core Java Basics exercises
- Practice Automorphic Number Check in Java
- Practice Binary to Decimal in Java
- Practice Prime Factorization in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler