Search code examples
javacompiler-errorsincompatibletypeerror

incompatible vs incomparable type


I am confused with these two types of error message in java.

For incompatible types, it might occur in the following scenario

if(integer=="String")

In what scenario will I get a incomparable type in java? Whats the main difference between these two?


Solution

  • Incomparable means that you are trying to compare two different types which is not legal. An example:

    Integer i = new Integer(8);
    if( i == "Foo" ){}
    

    It will show incomparable types: java.lang.Integer and java.lang.String because Java compiler can't compare two different types (in this case Integer and String).

    Now incompatible means that the compiler tried to perform a operation over a variable and that variable is incompatible with the operation. An example:

    public static String foo(int a){
        return a;
    }
    

    Obviously you can't return a int value as a String without a proper cast, return operation in this case needs a String and its been giving and int so return operation is incompatible with int data type.

    In short, incompatible refers to data types that can't make a specific operation and incomparable refers to a pair of data types that can't be compared.