I'm using eclipse java ee to perform java programming.
I had the following line of code in one of my functions:
Long result = -1;
I got the following error:
Type mismatch: cannot convert from int to Long
I can't quite understand why when i add a number to the variable it provides this error.
How can this issue be resolved and why did it happen in the first place?
Java int can be converted to long in two simple ways:Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.
int/long compare always works. The 2 operands are converted to a common type, in this case long and all int can be converted to long with no problems. int ii = ...; long ll = ...; if (ii < ll) doSomethings(); unsigned/long compare always works if long ranges exceeds unsigned .
There is no conversion between the object Long
and int
so you need to make it from long
. Adding a L
makes the integer -1
into a long
(-1L
):
Long result = -1L;
However there is a conversion from int
a long
so this works:
long result = -1;
Therefore you can write like this aswell:
Long result = (long) -1;
Converting from a primitive (int
, long
etc) to a Wrapper object (Integer
, Long
etc) is called autoboxing, read more here.
-1
can be auto-boxed to an Integer.
Thus:
Integer result = -1;
works and is equivalent to:
Integer result = Integer.valueOf(-1);
However, an Integer can't be assigned to a Long, so the overall conversion in the question fails.
Long result = Integer.valueOf(-1);
won't work either.
If you do:
Long result = -1L;
it's equivalent (again because of auto-boxing) to:
Long result = Long.valueOf(-1L);
Note that the L
makes it a long
literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With