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 8 and uses digits from 0 to 7. Octal representation is as follows 0, 1, 2, 3, 4, 5, 6, 7.

Hexadecimal numbers is a numeral system with a radix or 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 first create two String variables ‘strOctal’, ‘strHexa’ and integer variable ‘deci’.

In the next step get input from user, that is, user enters octal number using nextLine() method of Scanner class. This octal number is stored in String variable ‘strOctal’.

Now this String variable ‘strOctal’ value is passed as an argument to Integer.parseInt(String s, int radix) method. Now this value is stored in integer variable ‘deci’.

Then this integer variable ‘deci’ value is passed as an argument to Integer.toHexString() method. This method returns the string representation of the unsigned integer value represented by the argument in hexadecimal (base 16).

Finally print hexadecimal value on the console. Here’s the java program to convert octal to hexadecimal.

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


Output:

Please enter octal number: 237
Hexadecimal value of 237 is: 9f

Please enter octal number: 667
Hexadecimal value of 667 is: 1b7


Also read – Strings in java