Search code examples
javaintcompareto

Can I use the compareTo to compare two values of type int?


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"


Solution

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