1public class DecimalToBinaryExample2{
2public static void toBinary(int decimal){
3 int binary[] = new int[40];
4 int index = 0;
5 while(decimal > 0){
6 binary[index++] = decimal%2;
7 decimal = decimal/2;
8 }
9 for(int i = index-1;i >= 0;i--){
10 System.out.print(binary[i]);
11 }
12System.out.println();//new line
13}
14public static void main(String args[]){
15System.out.println("Decimal of 10 is: ");
16toBinary(10);
17System.out.println("Decimal of 21 is: ");
18toBinary(21);
19System.out.println("Decimal of 31 is: ");
20toBinary(31);
21}}
1Convert decimal to binary using toBinaryString() method
2public class DecimalToBinary
3{
4 public static void main(String[] args)
5 {
6 System.out.println("decimal to binary using toBinaryString() 104: ");
7 // to binary string java
8 System.out.println(Integer.toBinaryString(104));
9 System.out.println("\ndecimal to binary using toBinaryString() 554: ");
10 // tobinarystring
11 System.out.println(Integer.toBinaryString(554));
12 System.out.println("\ndecimal to binary using toBinaryString() 644: ");
13 System.out.println(Integer.toBinaryString(644));
14 }
15}
1Convert decimal to binary using stack in java
2import java.util.*;
3public class DecimalBinaryExample
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 Stack<Integer> numStack = new Stack<Integer>();
9 System.out.println("Please enter a decimal number : ");
10 int number = sc.nextInt();
11 while(number != 0)
12 {
13 int a = number % 2;
14 numStack.push(a);
15 number /= 2;
16 }
17 System.out.println("Binary number : ");
18 while(!(numStack.isEmpty()))
19 {
20 System.out.print(numStack.pop());
21 }
22 System.out.println();
23 sc.close();
24 }
25}