Java 17 Recipes


-18. Writing Readable Numeric Literals


Download 3.2 Mb.
Pdf ko'rish
bet89/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   85   86   87   88   89   90   91   92   ...   245
Bog'liq
Java 17 Recipes

4-18. Writing Readable Numeric Literals
 Problem
Some of the numeric literals in your application are rather long and you want to make it 
easier to tell how large a number is at a glance.
 Solution
Use underscores in place of commas or decimals in larger numbers to make them more 
readable. The following code shows some examples of making your numeric literals 
more readable by using underscores in place of commas.
public static void main(String[] args) {
int million = 1_000_000;
int billion = 1_000_000_000;
float ten_pct = 1_0f;
double exp = 1_234_56.78_9e2;
System.out.println(million);
System.out.println(billion);
System.out.println(ten_pct);
System.out.println(exp);
}
The output is:
1000000
1000000000
10.0
1.23456789E7
Note decimal point values automatically default to a double value unless a 
trailing “f” indicates that the value is a float.
Chapter 4 Numbers aNd dates


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.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   85   86   87   88   89   90   91   92   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling