Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Long result = -1: cannot convert from int to long

Tags:

java

casting

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?

like image 516
ufk Avatar asked Dec 14 '10 08:12

ufk


People also ask

Can int be converted to long in java?

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.

Can we compare int and long 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 .


2 Answers

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.

like image 185
dacwe Avatar answered Sep 22 '22 13:09

dacwe


-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.

like image 22
Matthew Flaschen Avatar answered Sep 20 '22 13:09

Matthew Flaschen