Core Java

Java puzzlers from OCA part 2

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.

01
02
03
04
05
06
07
08
09
10
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.

01
02
03
04
05
06
07
08
09
10
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.

01
02
03
04
05
06
07
08
09
10
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.

Published on Java Code Geeks with permission by Sezin Karli, partner at our JCG program. See the original article here: java puzzlers from oca part 2

Opinions expressed by Java Code Geeks contributors are their own.

Sezin Karli

Mathematics Engineer & Computer Scientist with a passion for software development. Avid learner for new technologies. Currently working as Senior Software Engineer at Sahibinden.com.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button