Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why the "long" primitive type does not accept a simple number?

I got a method that receives a long type parameher, and I try to call it passing 1:

contato.setId(1);

And I receive this:

The method setId(Long) in the type Contato is not applicable for the arguments (int).

But, isn't 1 a long number as well? Isn't it inside the long scope??

PS: Just to say, I solved the problem with this code:

Integer y = 1;
long x = y.longValue();
contato.setId(x);

It's just a didatic question.

like image 979
Mr Guliarte Avatar asked Feb 05 '15 20:02

Mr Guliarte


2 Answers

You should use contato.setId(1L); (notice the "L" suffix)

The literal "1" represents a primitive int value, which is casted to an java.lang.Integer wrapper class.

like image 114
rmuller Avatar answered Sep 22 '22 12:09

rmuller


long is a datatype that contains 64bits (not to be confused with the Object Long!) vs. an int (32 bits), so you can't use a simple assignment from int to long. See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

In order to see how to declare the various datatypes, you should check specifically the following table:

Datatype    Default Value
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char        '\u0000'
Object      null
boolean     false

So, for your case, long should be declared with the number followed by an L, for instance:

long x = 100L;

Further, doing what you're doing with autoboxing:

Integer y = 1;
long x = y.longValue();

is not only unnecessary - it's very wasteful as well. So, for example, if you'll do it in a loop (many times) your code will be slower in order of magnitude!

like image 38
Nir Alfasi Avatar answered Sep 22 '22 12:09

Nir Alfasi