octal to hexadecimal in java

Let’s learn octal to hexadecimal in java.

octal to hexadecimal in java

Octal numbers are computer based number system with base eight. Octal representation is as follows 0, 1, 2, 3, 4, 5, 6, 7.

Hexadecimal numbers are numbers with base 16 number system.

Hexadecimal representation is as follows 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.

In the below java program user enters octal number using nextLine() method of Scanner class.

This octal number is stored in String variable ‘strOctalNumber’.

In the next step first octal number is converted to decimal number.

Then this decimal number is converted to hexadecimal number using Integer.toHexString() method.

Here’s the program to convert octal to hexadecimal.

import java.util.Scanner;
public class OctalToHexadecimal
{
   public static void main(String[] args)
   {
      String strOctalNumber, strHexNumber;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter octal number: ");
      strOctalNumber = sc.nextLine();
      int decimalNumber = Integer.parseInt(strOctalNumber, 8);
      strHexNumber = Integer.toHexString(decimalNumber);
      System.out.print("Hexadecimal value of " + strOctalNumber + " is: \n");
      System.out.print(strHexNumber);
      sc.close();
   }
}


Output:

Please enter octal number: 644
Hexadecimal value of 644 is:
1a4


Also read – Strings in java