Convert Decimal to Binary Program in Java

Advertisements

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 Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements