For converting decimal number to binary, initially we push all the binary digits formed into the stack. After the entire number has been converted into the binary form, we pop one digit at a time from the stack and print it. Therefore we get the decimal number converted into its proper binary form.
Here is the source code of the Java program to convert decimal number to binary using stacks. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
* Java Program to Convert a Decimal Number
* to Binary Number using Stacks
/* DecimalToBinaryUsingStacks */
public class DecimalToBinaryUsingStacks
public static void main(String args)
Scanner scan = new Scanner(System.in);
/* Creating Stack object */
Stack<Integer> stk = new Stack<Integer>();
/* Accepting number */
System.out.println("Enter decimal number");
int num = scan.nextInt();
while (num != 0)
int d = num % 2;
num /= 2;
/* Print Binary equivalent */
System.out.print("\nBinary equivalent = ");
while (!(stk.isEmpty() ))
Enter decimal number 12345 Binary equivalent = 11000000111001 Enter decimal number 99 Binary equivalent = 1100011 Enter decimal number 24162 Binary equivalent = 101111001100010 Enter decimal number 347562318 Binary equivalent = 10100101101110110000101001110
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
If you liked this Java Program, kindly share, recommend or like below!