on Leave a Comment

Java Program to Convert Decimal to Binary

This java program converts decimal number into binary number. First you have to enter a decimal number, then number will convert into its equivalent binary number and finally display on the screen.

Java program to convert decimal to binary

import java.util.Scanner;

public class DecimalToBinary
{
    public static void main(String args[])
    {
        int decimal;
        int binary[] = new int[100];
        Scanner scan = new Scanner(System.in);
  
        System.out.print("Enter a Decimal Number : ");
        decimal = scan.nextInt();

        int i = 1, num;
  
        num = decimal;
  
        while(num != 0)
        {
            binary[i++] = num%2;
            num = num/2;
        }
  
        System.out.print("Binary Equivalent of " + decimal + " is : ");
        for(int j=i-1; j>0; j--)
        {
            System.out.print(binary[j]);
        }
    }
}

Output:

Enter a Decimal Number : 25
Binary Equivalent of 25 is : 11001

Java Program to Convert Decimal to Binary Using toBinaryString() Method

import java.util.Scanner;

public class DecimalToBinary
{
    public static void main(String args[])
    {
        int decimal;
        Scanner scan = new Scanner(System.in);
        
        System.out.print("Enter a Decimal Number : ");
        decimal = scan.nextInt();
                
        System.out.print("Binary Equivalent of " + decimal + " is : "+Integer.toBinaryString(decimal));
    }
}

Output:

Enter a Decimal Number : 30
Binary Equivalent of 30 is : 11110

0 comments:

Post a Comment