Java Program to Convert Octal To Binary

Write a Java program to convert octal to binary. In Java, we can use the parseInt with eight as the second argument to convert the octal string to a binary number.

package Remaining;

public class OctalToBinary1 {
	
	public static void main(String[] args) {
		
		String s1 = "15";
		String s2 = "45";
		String s3 = "122";
		
		int a = Integer.parseInt(s1, 8);
		int b = Integer.parseInt(s2, 8);
		int c = Integer.parseInt(s3, 8);
		
		System.out.println(Integer.toBinaryString(a));
		System.out.println(Integer.toBinaryString(b));
		System.out.println(Integer.toBinaryString(c));
	}
}
1101
100101
1010010

This Java example accepts the octal string and converts it to binary number using the Integer parseInt method.

package Remaining;

import java.util.Scanner;

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

		System.out.print("Please Enter Octal Number =  ");
		String octalString = sc.nextLine();
	
		int decimalVal = Integer.parseInt(octalString, 8);
		String binaryVal = Integer.toBinaryString(decimalVal);
		
		System.out.println("Octal To Binary Result = " + binaryVal);
	}
}
Java Program to Convert Octal To Binary 2

Java program to convert octal to binary using the for loop. The first for loop converts the octal to decimal and the second loop converts a decimal to binary number.

package Remaining;

import java.util.Scanner;

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

		System.out.print("Please Enter Octal Number =  ");
		int octalVal = sc.nextInt();
	
		int i, decimalVal = 0;
		long binaryVal = 0;
		
		for(i = 0; octalVal != 0; i++)
		{
			decimalVal = (int) (decimalVal + (octalVal % 10) * Math.pow(8, i));
			octalVal= octalVal / 10;
		}
		
		for(i = 1; decimalVal != 0; i = i * 10)
		{
			binaryVal = binaryVal + (decimalVal % 2) * i;
			decimalVal = decimalVal / 2;
		}
		
		System.out.println("Octal To Binary Result = " + binaryVal);
	}
}
Please Enter Octal Number =  124
Octal To Binary Result = 1010100

Java program to convert octal to binary using a while loop.

package Remaining;

import java.util.Scanner;

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

		System.out.print("Please Enter Octal Number = ");
		int octalVal = sc.nextInt();
	
		int i, j, decimalVal = 0;
		long binaryVal = 0;
		i = 0;
		
		while(octalVal != 0)
		{
			decimalVal = (int) (decimalVal + (octalVal % 10) * Math.pow(8, i++));
			octalVal= octalVal / 10;
		}
		j = 1; 
		while(decimalVal != 0)
		{
			binaryVal = binaryVal + (decimalVal % 2) * j;
			decimalVal = decimalVal / 2;
			j = j * 10;
		}
		
		System.out.println("Binary Result    = " + binaryVal);
	}
}
Please Enter Octal Number = 97
Binary Result    = 1001111