简体   繁体   中英

Integer and floating-point literals point and use?

I have read a section about literals and how they are used. For example you would add l or L at the end of a number to denote that the int is a long type. Same goes with the floating point numbers (f or F and d or D). What is the point of distinguishing this character at the end of a number. When we give the type does it not already know why specify again? So, what exactly is the point of adding this character to the end of a number? Where is it being used?

I have tried searching these questions on google and stack overflow already, but have not been able to receive a well developed answer to it.

The compiler knows how to treat the final result of an expression, but the individual literals (or variables) in an expression each have their own types, as do the intermediate values in the expression. For example:

static final double HALF = 1 / 2;

will actually have the value zero, because the literal 1 and 2 are int -typed, the division is an integer division that produces an int value of zero, and then Java turns that into a double . In contrast, in the expression

static final double HALF = 1d / 2;

the compiler knows to treat the first value as a double . The second value is promoted, Java does floating-point division, and the result is 0.5 as expected.

There are other situations, like autoboxing, where the compiler may treat equivalent values differently depending on their types; when passed to a method that takes an Object , 0 is an Integer , while 0L is a Long . This sort of situation occurs frequently in persistence/DAO code. Also, when compiling, the compiler evaluates compile-time constant expressions and puts their values directly into the code. The values of float and double expressions may be different because of the differing precisions of the types, and so you need to specify if you want a floating-point expression treated as just a float instead of as a double (the default).

You can not use a value greater than 2147483647 anywhere in java unless you have appended L or D to it. l makes the literal long type and d makes the literal double type.

eg System.out.println(2147483648); will result in an error as well as long num=2147483650; will also result in an error as these literals are no longer int type which the default type for the integers. So by appending l or d to a number you can use it as int or double type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM