148
How It Works
Sometimes working with large numbers can become cumbersome and difficult to read.
Since Java 7, underscores can be used with numeric literals to make code a bit easier to
read. The underscores can appear anywhere between digits in a numeric literal. This
allows underscores in place of commas or spaces to separate
the digits and make them
easier to read.
Note underscores cannot be placed at the beginning or the end of a number,
adjacent to a decimal point
or floating-point literal, before an
F or
L suffix, or in
positions where a string of digits is expected.
4-19. Declaring Binary Literals
Problem
You are working on an application that requires the declaration of binary numbers.
Solution
Use binary literals to make your code readable.
The following code segment
demonstrates the use of binary literals.
public static void main(String[] args) {
int bin1 = 0b1100;
short bin2 = 0B010101;
short bin3 = (short) 0b1001100110011001;
System.out.println(bin1);
System.out.println(bin2);
System.out.println(bin3);
}
Chapter 4 Numbers aNd dates
149
This result in the following output.
12
21
-26215
How It Works
Binary literals became part of the Java language starting in Java 7.
The byte, short, int,
and long types can be expressed using the binary number system. This feature can help
to make binary numbers easier to recognize in code.
To use the binary format, simply
prefix the number with 0b or 0B.
Do'stlaringiz bilan baham: