Welcome to the second part of Java Puzzlers from OCA. In this part we will see an interesting case about the underscore separator in numeric literals which came with Java 7.
In the below class you can see the separator underscore in the decimal literal. Also notice the class compiles now without a problem. Octal is the octal representation, binary is the binary and I'm sure you can't guess hex.
Octal literal is defined with 0, binary with 0b/0B and hex with 0x/0X. Ok then, let's begin putting _ for a better readability after them.
In the below class you can see the separator underscore in the decimal literal. Also notice the class compiles now without a problem. Octal is the octal representation, binary is the binary and I'm sure you can't guess hex.
public class Puzzler { public static void main(String[] args){ int decimal = 12_345; int octal = 04321; int binary = 0B1010; int hex = 0X4321A; } }
Octal literal is defined with 0, binary with 0b/0B and hex with 0x/0X. Ok then, let's begin putting _ for a better readability after them.
public class Puzzler { public static void main(String[] args){ int decimal = 12_345; int octal = 0_4321; int binary = 0B1010; int hex = 0X4321A; } }Neat. It compiles without a problem. Lets move to binary and hex.
public class Puzzler { public static void main(String[] args){ int decimal = 12_345; int octal = 0_4321; int binary = 0B_1010; int hex = 0X_4321A; } }Nope. You'll get "Illegal Underscore" there. I'm sure this is designed that way with something in mind, but it sure is a surprising behavior.