Java Program to Convert Binary to Octal

In this tutorial, we will write a java program to convert a binary number into octal using while loop. Before that, you must have knowledge of the following topics in C++.

Binary number

The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.

Octal number

The octal numbers are the numbers with base 8 and use the digits 0 to 7. Example: 8 in decimal is represented as 10 in octal, 25 as 31, and so on.

Let us go through a program for the Binary to Octal Conversion in java.


Java Program to Convert Binary to Octal using while loop

import java.util.Scanner;

public class Main
{
  public static void main(String args[])
  {
    int bin, rem, i = 0;
    int octalNum = 0, deciNum = 0;
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter a Binary Number: ");
    bin = sc.nextInt();

    while (bin != 0)
    {
      deciNum += (bin % 10) *Math.pow(2, i);
      ++i;
      bin /= 10;
    }

    i = 1;

    while (deciNum != 0)
    {
      octalNum += (deciNum % 8) *i;
      deciNum /= 8;
      i *= 10;
    }
    
    System.out.print("Equivalent Octal Value: " + octalNum);
    
  }
}

Output:

Enter a Binary Number: 1010
Equivalent Octal Value: 12