# Java program to convert Hexadecimal to octal number?

A hexadecimal number is used to computer system designers and programmers because they provide a human-friendly representation of binary code. Each hexadecimal digits represents four bits of binary digits. There are 16 symbols in hexadecimal, they are 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. Where A,B,C,D,E,F are single bit representation of decimal digit 10,11,12,13,14 and 15.

Each Hexadecimal digits are represented using only 4 bits, each group of bits having a distinct values 0000 and 1111 example F = 15 = 8+4+2+1. The equivalent binary number of Hexadecimal number gives below.

## Method for Hexadecimal to Octal Conversion

One of the best may to conversion in electronics and communications. Follow the below steps to perform hexadecimal digits to octal digit conversion:-

• step 1: Separate the digits of the given hex number, if it contains more than 1 digit.
• step 2: Find the equivalent binary number for each digit of the octal number. Add 0’s to the left if any of the binary equivalents is shorter than 4 bits.
• step 3: Write the all group’s binary numbers together, maintaining the same group.
• step 4: Separate the binary digits into groups, each containing 3 bits or digits from right to left. Add 0s to the left, if the last group contains less than 3 bits.
• step 5: Find the octal equivalent for each group.
• step 6: Write all octal equivalent of each digit together where keeping the same order provides the octal equivalent for the given hexadecimal.

#### Code:-

```import java.util.Scanner;

public class sample1 {
public static int hexdecimal(String s)
{
String digits = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
public static void main(String args[])
{
String hexdec_num;
int dec_num, i=1, j;
int octal_num[] = new int[100];
Scanner in = new Scanner(System.in);

hexdec_num = in.nextLine();

dec_num = hexdecimal(hexdec_num);

//decimal to octal

while(dec_num != 0)
{
octal_num[i++] = dec_num%8;
dec_num = dec_num/8;
}

System.out.print("Equivalent of octal number is: ");
for(j=i-1; j>0; j--)
{
System.out.print(octal_num[j]);
}
System.out.print("\n");
}
}
```