Search code examples
javahexliteralsoctal

when and why does programmers use octal and hexadecimal literals in java?


As a beginner, I am learning java, and I learned about literals. I got to know that octal and hex literals contain 3 and 4 bits. We can use them instead of binary literals to write more readable code. We can use _ (underscores) in binary or big integer literals to make them readable.

Then why do we actually use hex or octal?


Solution

  • You use hex because it's shorter than binary when doing bit-manipulation. No idea why anyone would use octal.

    E.g. when extracting the Green value from an RGB int, you would use (rgb >> 8) & 0xFF because 0xFF is much better than 255, 0377, and 0b11111111 in this context.