Here you will get program to convert decimal to binary in Java.
Below I have shared 3 different methods for java decimal to binary conversion.
Also Read: Convert Binary to Decimal in Java
Convert Decimal to Binary in Java
1. Integer.toString() Method
We can convert a decimal number to binary using toString() method of Integer class. This method takes two arguments, first argument is the decimal number and second is the base in which we want to convert. For binary the base is 2.
import java.util.Scanner; public class JavaD2B { public static void main(String args[]){ int number; Scanner sc = new Scanner(System.in); System.out.println("Enter a decimal number: "); number = sc.nextInt(); System.out.println("Binary number is " + Integer.toString(number, 2)); } }
Output
Enter a decimal number:
8
Binary number is 1000
2. Integer.toBinaryString()
It is another method of Integer class that can directly convert decimal to binary. See below program to know how to use it.
import java.util.Scanner; public class JavaD2B { public static void main(String args[]){ int number; Scanner sc = new Scanner(System.in); System.out.println("Enter a decimal number: "); number = sc.nextInt(); System.out.println("Binary number is " + Integer.toBinaryString(number)); } }
Output
Enter a decimal number:
10
Binary number is 1010
3. Own Logic
We can write our own logic for decimal to binary conversion in java. It can be done by following steps.
- Divide the number by 2 using % operator and store the remainder somewhere.
- Divide the number by 2 using / operator.
- Repeat above two steps until number becomes 0.
- Now print the remainders in reverse order.
Below program implements this simple algorithm.
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class JavaD2B { public static void main(String args[]){ int number; Scanner sc = new Scanner(System.in); ArrayList<String> binary = new ArrayList<String>(); System.out.println("Enter a decimal number: "); number = sc.nextInt(); while(number != 0){ binary.add(String.valueOf(number%2)); number /= 2; } Collections.reverse(binary); System.out.print("Binary number is "); for(String s : binary){ System.out.print(s); } } }
Output
Enter a decimal number:
2
Binary number is 10
Comment below if you have doubts or know any other way to convert decimal to binary in Java.