Weird Quirks of Java - E01- Historic Reasons in Language Design
In this brief episode, I want to give you a puzzle that is simple in itself, but also not very obvious. At the same time, this serves as an introduction to a new series exploring oddities of the Java programming language.
Your task is to guess what the output of the following programme will look like. The Solution and Explanation are found in the collapsable section below the code.
public class Magic {
public static void main(String []args) {
int magic = 023;
System.out.println(magic);
}
}
Solution and Explanation
The Solution is 19 - Congrats if you have guessed that correctly. But Why?
The design and syntax of the Java language is based on and influenced by the C programming language[1]. This design choice brings the implicit formatting and parsing of numbers in integer literals from C[2] to Java. This means that any number starting with 0 is treated as octal. The same is true for hexadecimal with a leading 0x.[3]
But what use is there for this?
This is still widely used in POSIX / Unix / Linux, which are mostly implemented in C.
Linux uses operation permission codes, e.g. for file permissions, by using octal-based coding notation[4].
drwxr-x--- 2 jeujeus jeujeus 2048 Oct 23 2023 blog
The following example above corresponds to the umask of 750 :
Octal Representation | Who Part | Permission Bits | Character Flags |
---|---|---|---|
7 | O | 111 | rwx |
5 | G | 101 | r-x |
0 | U | 000 | --- |
You can read more regarding Unix File Permissions at [5].
[1] - Oracle, Java Language Specification
[2] - Sonarsource, C static code analysis
[3] - StackOverflow, Java Octals
[4] - UnixWare 7 Documentation, Getting semaphores
[5] - NERSC Documentation, Unix File Permissions