Sitemap

Understanding Octal Numbers in Java

2 min readJul 26, 2024

--

The octal number system is a base-8 system, meaning it uses digits from 0 to 7. Digits 8 and 9 are not valid in octal representation. In Java, if an integer literal begins with a leading zero, it is interpreted as an octal number. Thus, the digits in such literals can only be between 0 and 7.

To denote an octal literal in Java code, prefix the number with a leading zero. For hexadecimal numbers, use the prefix 0x.

For example:

Octal Literal: 0757

Hexadecimal Literal: 0x1EF

Here’s an example demonstrating the different number systems and how they map to the same decimal value.

Press enter or click to view image in full size

Explanation:

  • Decimal: 255 is written directly as a base-10 number.
  • Hexadecimal: 0xFF is a base-16 number.F in hexadecimal is 15, so 0xFF equals 15*16^1 + 15*16^0 = 255 in decimal.
  • Octal: 0377 is a base-8 number. 0377 in base-8 is calculated as 3*8^2 + 7*8^1 + 7*8^0 = 192 + 56 + 7 = 255 in decimal.
  • Binary: 0b11111111 is a base-2 number. 0b11111111 in base-2 is calculated as 1*2^7 + 1*2^6 + 1*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 1*2^1 + 1*2^0 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 in decimal.

When you run this code, all the output values will show 255, demonstrating that all these different representations are equivalent in their decimal form.

Get Harshitha’s stories in your inbox

Join Medium for free to get updates from this writer.

To display an integer value in octal format, use the Integer.toOctalString(int) method. Conversely, to convert a string representing an octal number back into an integer, use Integer.parseInt(String value, int radix), specifying 8 as the radix.

Press enter or click to view image in full size

Output :

Octal: 747
Parsed Octal: 495

Explanation:

  1. Integer.toOctalString(decimal): Converts the decimal number 495 to its octal representation.495 in decimal is 747 in octal.
  2. Integer.parseInt(octalString, 8): Converts the octal string 747 back to its decimal form.747 in octal converts back to 495 in decimal.

Happy Reading!!

--

--