Java - int / long, float / double

I understand that "2.5" is automatically double, and in order to make it float, I need to do "2.5F" (or if F will be lowercase?), And that I should use float, say if I had a constant which only ever needed 2 decimal spaces (for example, β€œ0.08F” for PST Ontario tax), but I'm not sure if β€œ12” is int or long, but I know that β€œ12L” is but "long l = 12" and "long l = 12L" seem to compile for the same thing, and I use long if I need maximum floating point precision, and int if I know I don't need to exceed be limits int.

Please correct me if something is wrong there and answer the questions that I have.

+3
source share
4 answers

12 as a constant in java is an int.

The reason for the long compilation of l = 12 is that it is automatically expanded to long.

EDIT: As for your comment, there is nothing wrong with auto-extension, use what makes your code clearer, but just know what happens when you do the math on primitives. For example:

int i = 1213;
long l = 112321321L * i;

Long ones will have a completely different meaning, unless you explicitly put this first number as long, because Java will treat it as an integer math and cause an overflow.

+14
source

, float.

... "0.08F" PST Ontario

, BigDecimal. . Sun.

+7

12 int. , int, double, 2.5.

long x = 12;

, , int 12 long.

, 2.5F 12L, , . 1 , , .

+3

Note that while intliterals will automatically expand to longwhen assigning a variable long, you will need to use an explicit literal longwhen expressing a value greater than Integer.MAX_VALUE(2147483647) or less Integer.MIN_VALUE(-2147483648):

long x1 = 12; //OK
long x2 = 2147483648; // not OK! That not a valid int literal
long x3 = 2147483648L; // OK
+3
source

Source: https://habr.com/ru/post/1716512/


All Articles