0

I don't know what the problem is with the following code? In IntelliJ, at compile-time, an error occurs to the compareTo method and says that this method does not exist in the Number class.

Number x = new Integer(3);
System.out.println(x.intValue());
System.out.println((Integer)x.compareTo(new Integer(4)));

Doesn't it convert to an Integer object first and then the method is called?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
amz
  • 32
  • 6
  • 2
    No, it does not - method invocation comes first - check [Java casting order](https://stackoverflow.com/q/5762270/15244370) on this very site –  Mar 29 '21 at 15:19

2 Answers2

2

Doesn't it convert to an Integer object first and then the method is called?

No, it converts the result of the method to Integer. You'd need to call ((Integer)x).compareTo(new Integer(4)) instead.

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

No, you are trying to compare a number to an integer and then cast the result to integer. It is always preferred to use brackets to help the reading, or even better use the built in functions to get the variable in the desirable way

SgtOmer
  • 200
  • 1
  • 1
  • 8