Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...