0

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!

5
  • What do you think Integer.my_int.longValue() should do and why? Commented Jul 6, 2014 at 16:40
  • Integer.my_int.longValue(); should be ((Integer)my_int).longValue(); Commented Jul 6, 2014 at 16:41
  • 1
    int != Integer stackoverflow.com/questions/8660691/… Commented Jul 6, 2014 at 16:41
  • You could have also used Integer.valueof(my_int).longValue(); Commented Jul 6, 2014 at 16:42
  • Read this for a little reference: en.wikipedia.org/wiki/Primitive_wrapper_class Commented Jul 6, 2014 at 16:42

4 Answers 4

1

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

Also you should try this

((Integer)my_int).longValue();
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.