Binary to Octal Program in Java


Prev Tutorial Next Tutorial

Convert Binary to Octal Program in Java

There are two way to convert decimal number into octal number, which is given below;

  • Using predefined method Integer.toOctalString(int num)
  • Writing our own logic for conversion

Convert Binary to Octal in Java

import java.util.Scanner;
 
public class BinaryTOoctal
{
Scanner scan;
int num;
	
void getVal() 
{	
System.out.println("Binary to Octal");
scan = new Scanner(System.in);
	
System.out.println("\nEnter the number :");
num = Integer.parseInt(scan.nextLine(), 2);
}	
void convert() 
{
String octal = Integer.toOctalString(num);
System.out.println("Octal Value is : " + octal);
}
}
 
class MainClass 
{
	
public static void main(String args[]) 
{
Binary_Octal obj = new Binary_Octal();
obj.getVal();
obj.convert();
}
}

Output

Binary to Octal

Enter the number :
1010
Octal Value is : 12

Convert Binary to Octal in Java

import java.util.Scanner;

public class BinaryTOoctal
{
 public static void main(String args[])
 {
 int binnum, rem, quot, i=1, j;
 int octnum[] = new int[100];
 Scanner scan = new Scanner(System.in);
		
 System.out.print("Enter Binary Number : ");
 binnum = scan.nextInt();
		
 quot = binnum;
		
 while(quot != 0)
 {
 octnum[i++] = quot%8;
 quot = quot/8;
 }
		
 System.out.print("Equivalent Octal Value of " +binnum+ " is :\n");
 for(j=i-1; j>0; j--)
 {
 System.out.print(octnum[j]);
 }
}
}

Output

Enter Binary Number : 11
Equivalent Octal Value of 11 is :13

Syntax to compile and run java program

Syntax

for compile -> c:/>javac BinaryTOoctal.java
for run -> c:/>java BinaryTOoctal

Prev Tutorial Next Tutorial

Advertisements
Download Projects