Search This Blog

Sunday, 6 November 2016

Using underscores in literals

Using underscores in literals to improve code readability

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, to separate groups of digits in numeric literals, which can improve the readability of your code.

This is intended to improve the readability of code by separating digits of a literal into significant groups at almost any arbitrary place that meets the needs of the developer. The underscore can be applied to primitive data types in any supported base (binary, octal, hexadecimal, or decimal), and to
both integer and floating-point literals.

Example to show ways you can use the underscore in numeric literals:

            long creditCardNumber = 1234_5678_9012_3456L;
            long socialSecurityNumber = 999_99_9999L;
            float pi = 3.14_15F;
            long hexBytes = 0xFF_EC_DE_5E;
            long hexWords = 0xCAFE_BABE;
            long maxLong = 0x7fff_ffff_ffff_ffffL;
            byte nybbles = 0b0010_0101;
            long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the following places:
·         At the beginning or end of a number
·         Adjacent to a decimal point in a floating point literal
·         Prior to an F or L suffix
·         In positions where a string of digits is expected

The following are the examples of invalid underscore usages:
            long creditCardNumber = _12345_67890_09876_54321L;
            float pi = 3._14_15F;
long licenseNumber = 123_456_789_L;

No comments:

Post a Comment