What's the difference between the following?
long var1 = 2147483647L;
long var2 = 2147483648;
(or any primitive variable declaration) Does it have any performance issue with or without L? Is it mandatory?
What's the difference between the following?
long var1 = 2147483647L;
long var2 = 2147483648;
(or any primitive variable declaration) Does it have any performance issue with or without L? Is it mandatory?
In the first case you are assigning a long
literal to a long
variable (the L
or l
suffix indicates long
type).
In the second case you are assigning an int
literal (that's the default type when no suffix is supplied) to a long
variable (which causes an automatic type cast from int
to long
), which means you are restricted to the range from Integer.MIN_VALUE
to Integer.MAX_VALUE
(-2147483648
to 2147483647
).
That's the reason why
long var2 = 2147483648;
doesn't pass compilation (2147483648
is larger than Integer.MAX_VALUE
).
On the other hand
long var2 = 2147483648L;
would pass compilation.
For easy understanding each of the type have range in java.
By default every digit you entered in java is either byte
or short
or integer
.
short s = 32767;
byte b = 127;
int i = 2147483647;
So if you assign anything except from their range you'll get compilation error.
int i = 2147483648; //compilation error.
And when you write long longNumber = 2147483647;
though it falls in long range but internally java treat it as
long l = (int) 2147483647;
you wont get any errors.
But if we assign beyond the range of integer like
longNumber = 2147483648;
we will get compilation error as
long o = (int) 2147483648;
here java will try to convert the 2147483648 to int but it is not in int range so widening error is thrown. To indicate java that the number what we have written is beyond the integer range just append l or L to the end of the number. so java will wide his range till long and convert it as
long o = (long) 2147483648;
By default every floating point or digit with floating points (.) are size of double. So when you write some digits with (.) java treat as a double and it must be in double range. As we know the float range is smaller then double. so when you write
float f = 3.14;
though it falls in double range but internally java treat this assignment as
float f = (double) 3.14;
here you are assigning the double to float narrowing which is not correct. so either you have to convert the expression like that
float f = (float)3.14;
or
float f = 3.14f; // tell jvm to assign this in float range by appending **f** or **F**
If we don't mention the L
with the value then value is considered to be int
value.
It type casts the int
to long
automatically.