Java program to convert decimal to binary using toBinaryString and stack

Let’s learn (decimal to binary java) java program to convert decimal to binary using toBinaryString and stack.

Java program to convert decimal to binary using toBinaryString and stack

Java decimal to binary is the most common java interview question.

Also read – decimal to binary logic

There are two ways in converting decimal to binary java, one using toBinaryString() method and another using stack.

Using toBinaryString() method

public class DecimalToBinary
{
   public static void main(String[] args)
   {
      System.out.println("Decimal to binary of 104 : ");
      // to binary string java
      System.out.println(Integer.toBinaryString(104));
      System.out.println("\nDecimal to binary of 554 : ");
      // tobinarystring
      System.out.println(Integer.toBinaryString(554));
      System.out.println("\nDecimal to binary of 644 : ");
      System.out.println(Integer.toBinaryString(644));
   }
}

Output:

Decimal to binary of 104 : 1101000

Decimal to binary of 554 : 1000101010

Decimal to binary of 644 : 1010000100

Using stack

Similarly here’s the java decimal to binary using stack,

// decimal to binary conversion in java
import java.util.*;
public class DecimalBinaryExample
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);                
      Stack<Integer> numStack = new Stack<Integer>();     
      System.out.println("Please enter a decimal number : ");
      int number = sc.nextInt();
      while(number != 0)
{
int a = number % 2;
numStack.push(a);
number /= 2;
}
System.out.print("Binary number : ");
while(!(numStack.isEmpty()))
{
System.out.print(numStack.pop());
}
System.out.println();
sc.close();
}
}

Output:

Please enter a decimal number : 665
Binary number : 1010011001