Convert Decimal to Binary Program in Java


Prev Tutorial Next Tutorial

Convert Decimal to Binary Example in Java

This code is design using two methods, create own logic and use predefined method. Binary number system contain only two digits 0 and 1 and it have base 2.

Decimal Number representation of a real number using the base ten and decimal notation.

Binary Number contains only 0 and 1.

Convert Decimal to Binary in Java

import java.util.Scanner;
import java.util.Stack;

public class DecimalTObinary 
{
 public static void main(String[] args) 
{
Scanner in = new Scanner(System.in);
    
// Create Stack object
Stack<Integer> stack = new Stack<Integer>();
     
//Take  User input from keyboard
 System.out.println("Enter any Decimal Number: ");
 int num = in.nextInt();
while (num != 0)
{
   int d = num % 2;
   stack.push(d);
   num /= 2;
 } 
 System.out.print("\nBinary is:");
while (!(stack.isEmpty() ))
 {
   System.out.print(stack.pop());
 }
System.out.println();
}
}

Output

Enter any Decimal Number: 
7
Binary is: 111

Syntax to compile and run java program

Syntax

for compile -> c:/>javac DecimalTObinary.java
for run -> c:/>java DecimalTObinary

Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements