Emerrias
Emerrias

Reputation: 15

Using the Integer object Java?

I was just reading over some Java code and asked myself why this piece of code:

int my_int = 100;
Long my_long = Integer.my_int.longValue();

would not work giving me the error, "my_int can not be resolved or is not a field" ; however this code would work:

Integer my_integer = new Integer(100);
Long my_long = my_integer.longValue();

Please explain!

Upvotes: 0

Views: 80

Answers (4)

SparkOn
SparkOn

Reputation: 8946

Long my_long = Integer.my_int.longValue();

gives you an error because my_int is not an static field of Integer class so abviously the compiler cannot resolve it. One thing to can do to solve it is cast it to Integer and call it longValue() method:

Long my_long = ((Integer) my_int).longValue();

Moreover int is primitive type and The Integer class wraps a value of the primitive type int in an object.

While in Long my_long = my_integer.longValue(); works because you are trying to call the longValue() of Integer class and it returns the value of this Integer as a long which is perfectly valid.

Upvotes: 0

Brett Okken
Brett Okken

Reputation: 6306

Integer.my_int is attempting to reference a static variable (field) named my_int on the class Integer. No such variable/field exists, which is why you get the compilation error.

The following would also work:

int my_int = 100;
Long my_long = Integer.valueOf(my_int).longValue();

However, the following is probably the better solution:

int my_int = 100;
Long my_long = Long.valueOf(my_int);

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

You should remember that Integer is a class and int is a primitive type.

Also you should try this

((Integer)my_int).longValue();

Upvotes: 1

Because the Integer class does not have a static method named my_int.

You need to pass it in as a parameter to e.g. Integer.valueOf(my_int).

Upvotes: 0

Related Questions