Write a Program to convert Binary to Octal number system


The program starts by importing the Scanner class from the java.util package, which allows user input to be read from the console. Then a class named Binary_Octal is defined, which contains the main method that executes the program.

Inside the main method, the program declares and initializes variables to be used in the conversion process. The bin variable stores the binary number entered by the user, and the i variable is an index used to keep track of the current digit being converted. The oct array stores the octal digits in reverse order.

The program then prompts the user to enter a binary number using System.out.print and reads the input value using the Scanner class.

After that, the program enters a while loop that runs as long as the binary number is not equal to 0. Inside the loop, the program calculates the remainder of the division of the binary number by 8 and stores it in the oct array at the current index. The i index is then incremented, and the binary number is divided by 8 to move to the next digit.

After the loop completes, the oct array contains the octal representation of the binary number in reverse order. The program then uses a for loop to iterate through the oct array in reverse order and print each digit to the console using System.out.print.

Source Code

import java.util.Scanner;
public class Binary_Octal
{
	public static void main(String args[])
	{
		int bin,i=1, j;
		int oct[] = new int[100];
		Scanner input = new Scanner(System.in);  
		System.out.print("Enter the Binary Number : ");
		bin = input.nextInt(); 
		while(bin != 0)
		{
			oct[i++] = bin%8;
			bin = bin/8;
		}
		System.out.print("Octal Number : ");
		for(j=i-1; j>0; j--)
		{
			System.out.print(oct[j]);
		}
	}
}

Output

Enter the Binary Number : 1010
Octal Number : 1762

Example Programs