-3

In this problem I want to compare the two variables int "a" and "b" with the compareTo, but there is an error. How can I fix it? Thank you for your support.

public static void main(String[] args) {
    int a=5;
    int b=5;
    if (a.compareTo(b));
}

This is the error: "Cannot invoke compareTo(int) on the primitive type int"

Tommy
  • 37
  • 5

1 Answers1

0

int is one of the few primitive types that are built into the Java language, and as you noticed, primitives cannot contain methods.

You can wrap them in the non-primitive Integer type, which is a class, and then do the comparison:

Integer.valueOf(a).compareTo(Integer.valueOf(b))

Better (because it doesn't create useless objects) is to use the static method that that class offers, which does take primitive ints as arguments:

Integer.compare(a, b)
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Thank you for your response. Can you tell me why this question was closed and no longer accepts answers? Thank you. – Tommy May 07 '20 at 16:55
  • Probably because you initially didn't post the actual error message you were getting, and because a very similar (duplicate) question already exists as linked in the comment by @jhamon. – Thomas May 08 '20 at 10:20