Java Program to Convert Decimal To Binary

Write a Java program to convert decimal to binary. In this programming language, we can use the integer toBinaryString method to convert decimal numbers into binary strings.

package Remaining;

public class DecimalToBinary1 {
	
	public static void main(String[] args) {
		
		int a = 10;
		int b = 25;
		int c = 77;
		int d = 135;
		
		System.out.println(Integer.toBinaryString(a));
		System.out.println(Integer.toBinaryString(b));
		System.out.println(Integer.toBinaryString(c));
		System.out.println(Integer.toBinaryString(d));
	}
}
1010
11001
1001101
10000111

Java Program to Convert Decimal To Binary

This example accepts a decimal number and converts it to a binary string using the toBinaryString.

package Remaining;

import java.util.Scanner;

public class DecimalToBinary2 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);

		System.out.print("Please Enter Decimal Number =  ");
		int decimal = sc.nextInt();
	
		String BinaryVal = Integer.toBinaryString(decimal);
		System.out.println("Decimal To Binary Result    = " + BinaryVal);
	}
}
Java Program to Convert Decimal To Binary using toBinaryString

This program will convert decimal to binary using the for loop. This example uses the integer array to hold the binary values from the for loop by dividing the numbers by 2.

package Remaining;

import java.util.Scanner;

public class DecimalToBinary3 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		int i, j, decimal;
		
		sc= new Scanner(System.in);

		System.out.print("Number =  ");
		decimal = sc.nextInt();
			
		int binaryVal[] = new int[30];
		
		for(i = 0; decimal > 0; i++)
		{
			binaryVal[i] = decimal % 2;
			decimal = decimal / 2;
		}
	
		System.out.print("Result  = ");
		for(j = i - 1; j > 0; j--)
		{
			System.out.print(binaryVal[j]);
		}
	}
}
Number =  245
Result  = 1111010


Number =  339
Result  = 10101001

Java Program to convert decimal to binary using a while loop.

package Remaining;

import java.util.Scanner;

public class DecimalToBinary4 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		int j, decimal, i = 1;
		
		sc= new Scanner(System.in);

		System.out.print("Number =  ");
		decimal = sc.nextInt();
			
		int binaryVal[] = new int[30];
		
		while(decimal != 0)
		{
			binaryVal[i++] = decimal % 2;
			decimal = decimal / 2;
		}
	
		System.out.print("Result  = ");
		j = i - 1;
		while(j > 0)
		{
			System.out.print(binaryVal[j]);
			j--;
		}
	}
}
Number =  98
Result  = 1100010

Number =  175
Result  = 10101111