VOOZH about

URL: https://www.javacodegeeks.com/2020/04/java-puzzlers-from-oca-part-2.html

⇱ Java puzzlers from OCA part 2 - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Sezin Karli
Sezin Karli
April 23rd, 2020Last Updated: April 21st, 2020
0 69 1 minute read

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

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

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz