Welcome to the World of Online Learning:
Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Write a Java Program to Convert Binary Number to Decimal and vice-versa
PROGRAM: Java Program to Convert Binary Number to Decimal and vice-versa
/*Java Program to Convert Binary Number to Decimal and vice-versa*/
1: Binary to Decimal Conversion Using Custom Method
class Main {
public static void main(String[] args) {
// binary number
long num = 110110111;
// call method by passing the binary number
int decimal = convertBinaryToDecimal(num);
System.out.println(“Binary to Decimal”);
System.out.println(num + ” = ” + decimal);
}
public static int convertBinaryToDecimal(long num) {
int decimalNumber = 0, i = 0;
long remainder;
while (num != 0) {
remainder = num % 10;
num /= 10;
decimalNumber += remainder * Math.pow(2, i);
++i;
}
return decimalNumber;
}
}
2: Binary to Decimal Conversion Using parseInt()
class Main {
public static void main(String[] args) {
// binary number
String binary = “01011011”;
// convert to decimal
int decimal = Integer.parseInt(binary, 2);
System.out.println(binary + ” in binary = ” + decimal + ” in decimal.”);
}
}
3: Decimal to Binary Conversion using Custom Method
class Main {
public static void main(String[] args) {
// decimal number
int num = 19;
System.out.println(“Decimal to Binary”);
// call method to convert to binary
long binary = convertDecimalToBinary(num);
System.out.println(“\n” + num + ” = ” + binary);
}
public static long convertDecimalToBinary(int n) {
long binaryNumber = 0;
int remainder, i = 1, step = 1;
while (n!=0) {
remainder = n % 2;
System.out.println(“Step ” + step++ + “: ” + n + “/2”);
System.out.println(“Quotient = ” + n/2 + “, Remainder = ” + remainder);
n /= 2;
binaryNumber += remainder * i;
i *= 10;
}
return binaryNumber;
}
}
4: Decimal to Binary Conversion using toBinaryString()
class Main {
public static void main(String[] args) {
// decimal number
int decimal = 91;
// convert decimal to binary
String binary = Integer.toBinaryString(decimal);
System.out.println(decimal + ” in decimal = ” + binary + ” in binary.”);
}
}