Understanding Octal Numbers in Java
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.
Explanation:
- Decimal:
255is written directly as a base-10 number. - Hexadecimal: 0xFF is a base-16 number.
Fin hexadecimal is15, so0xFFequals15*16^1 + 15*16^0 = 255in decimal. - Octal:
0377is a base-8 number.0377in base-8 is calculated as3*8^2 + 7*8^1 + 7*8^0 = 192 + 56 + 7 = 255in decimal. - Binary:
0b11111111is a base-2 number.0b11111111in base-2 is calculated as1*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 = 255in 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.
Output :
Octal: 747
Parsed Octal: 495
Explanation:
Integer.toOctalString(decimal): Converts the decimal number495to its octal representation.495in decimal is747in octal.Integer.parseInt(octalString, 8): Converts the octal string747back to its decimal form.747in octal converts back to495in decimal.
Happy Reading!!





