Write a Java Program to Convert Binary Number to Octal and vice-versa

Converting numbers between different number systems is a fundamental concept in computer programming.

Java provides built-in functions to convert numbers between binary, octal, decimal, and hexadecimal number systems.

In this tutorial, we will discuss how to convert binary numbers to octal numbers and vice versa using Java.


Binary to Octal Conversion

Binary numbers are base-2 numbers, which means they only use two digits, 0 and 1.

Octal numbers are base-8 numbers, which means they use eight digits, 0 to 7.

To convert a binary number to an octal number, we can group the binary digits into groups of three from the right and then replace each group with its octal equivalent.

Here’s the Java program to convert a binary number to an octal number:

import java.util.Scanner;

public class BinaryToOctal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        String binaryString = scanner.nextLine();
        scanner.close();
        int binary = Integer.parseInt(binaryString, 2);
        String octalString = Integer.toOctalString(binary);
        System.out.println("Octal equivalent: " + octalString);
    }
}

In this program, we first ask the user to input a binary number.

Then, we convert the binary number to an integer using the parseInt() method with the radix of 2.

Finally, we use the toOctalString() method to convert the integer to an octal string.

Octal to Binary Conversion

To convert an octal number to a binary number, we can replace each octal digit with its binary equivalent, which is a three-digit binary number.

Here’s the Java program to convert an octal number to a binary number:

import java.util.Scanner;

public class OctalToBinary {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an octal number: ");
        String octalString = scanner.nextLine();
        scanner.close();
        int octal = Integer.parseInt(octalString, 8);
        String binaryString = Integer.toBinaryString(octal);
        System.out.println("Binary equivalent: " + binaryString);
    }
}

In this program, we first ask the user to input an octal number.

Then, we convert the octal number to an integer using the parseInt() method with the radix of 8.

Finally, we use the toBinaryString() method to convert the integer to a binary string.


Conclusion

In this tutorial, we have discussed how to convert binary numbers to octal numbers and vice versa using Java.

By using the built-in functions provided by Java, we can easily perform these conversions without having to write complex algorithms.