Sunday, April 19, 2020

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.

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.

1 comment:

  1. Check this out here...
    https://www.journaldev.com/607/underscores-in-numeric-literals-java-7-feature

    ReplyDelete