Blog |

How to Handle the Incompatible Types Error in Java

How to Handle the Incompatible Types Error in Java
Table of Contents

Introduction to Data Types & Type Conversion

Variables are memory containers used to store information. In Java, every variable has a data type and stores a value of that type. Data types, or types for short, are divided into two categories: primitive and non-primitive. There are eight primitive types in Java: byte, short, int, long, float, double, boolean and char. These built-in types describe variables that store single values of a predefined format and size. Non-primitive types, also known as reference types, hold references to objects stored somewhere in memory. The number of reference types is unlimited, as they are user-defined. A few reference types are already baked into the language and include String, as well as wrapper classes for all primitive types, like Integer for int and Boolean for boolean. All reference types are subclasses of java.lang.Object [1].

In programming, it is commonplace to convert certain data types to others in order to allow for the storing, processing, and exchanging of data between different modules, components, libraries, APIs, etc. Java is a statically typed language, and as such has certain rules and constraints in regard to working with types. While it is possible to convert to and from certain types with relative ease, like converting a char to an int and vice versa with type casting [2], it is not very straightforward to convert between other types, such as between certain primitive and reference types, like converting a String to an int, or one user-defined type to another. In fact, many of these cases would be indicative of a logical error and require careful consideration as to what is being converted and how, or whether the conversion is warranted in the first place. Aside from type casting, another common mechanism for performing type conversion is parsing [3], and Java has some predefined methods for performing this operation on built-in types.

double myDouble = 9; // Automatic casting (int to double)
int myInt = (int) 9.87d; // Manual casting (double to int)
boolean myBoolean = Boolean.parseBoolean("True"); // Parsing with a native method (String to boolean)

System.out.println(myDouble);   // 9.0
System.out.println(myInt);      // 9
System.out.println(myBoolean);  // true

 

Incompatible Types Error: What, Why & How?

The incompatible types error indicates a situation where there is some expression that yields a value of a certain data type different from the one expected. This error implies that the Java compiler is unable to resolve a value assigned to a variable or returned by a method, because its type is incompatible with the one declared on the variable or method in question. Incompatible, in this context, means that the source type is both different from and unconvertible (by means of automatic type casting) to the declared type.

This might seem like a syntax error, but it is a logical error discovered in the semantic phase of compilation. The error message generated by the compiler indicates the line and the position where the type mismatch has occurred and specifies the incompatible types it has detected. This error is a generalization of the method X in class Y cannot be applied to given types and the constructor X in class Y cannot be applied to given types errors discussed in [4].

The incompatible types error most often occurs when manual or explicit conversion between types is required, but it can also happen by accident when using an incorrect API, usually involving the use of an incorrect reference type or the invocation of an incorrect method with an identical or similar name.

 

Incompatible Types Error Examples

Explicit type casting

Assigning a value of one primitive type to another can happen in one of two directions. Either from a type of a smaller size to one of a larger size (upcasting), or from a larger-sized type to a smaller-sized type (downcasting). In the case of the former, the data will take up more space but will be intact as the larger type can accommodate any value of the smaller type. So the conversion here is done automatically. However, converting from a larger-sized type to a smaller one necessitates explicit casting because some data may be lost in the process.

Fig. 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario. By capturing this error, the compiler prevents accidental loss of data and forces the programmer to be deliberate about the conversion. The same principle applies to downcasting reference types, although the process is slightly different as polymorphism gets involved [5].

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "\tb: " + b);

    int x = a;
    int y = b;
    System.out.println("x: " + x + "\ty: " + y);
  }
}
IncompatibleTypesCasting.java:10: error: incompatible types: possible lossy conversion from double to int
    int x = a;
            ^
IncompatibleTypesCasting.java:11: error: incompatible types: possible lossy conversion from double to int
    int y = b;
            ^
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class IncompatibleTypesCasting {

  public static void main(String... args) {
    double a = 10.5;
    double b = 5.0;
    System.out.println("a: " + a + "\tb: " + b);

    int x = (int) a;
    int y = (int) b;
    System.out.println("x: " + x + "\ty: " + y);
  }
}
a: 10.5 b: 5.0
x: 10   y: 5

Figure 1: Incompatible types when downcasting (a) error and (b) resolution

 

Explicit parsing

Parsing is a more complex process than type casting as it involves analyzing the underlying structure of a given data before converting it into a specific format or type. For instance, programmers often deal with incoming streams of characters, usually contained in a string that needs to be converted into specific types to make use of in the code. A common scenario is extracting numeric values from a string for further processing, which is where parsing is routinely used.

The main method in Fig. 2(a) declares the variable date which holds the current date as a String in the yyyy-MM-dd format. In order to get the year value into a separate variable it is necessary to “parse” the first 4 characters of the string, and this can be accomplished by splitting the string by specifying the “-” character as a delimiter and then accessing the first element (line 9 in Fig. 2(a)). With this, the year value has been successfully parsed and stored into a new variable. Attempting to increase the value of this new variable and store the resulting value in a separate int variable triggers the incompatible types error (line 10 in Fig. 2(a)). This is because even though the year has been isolated from the date and parsed into a new variable, it is impossible to perform arithmetic operations on a variable of type String. Therefore, it is necessary to represent this value as a numeric type. The best way to do this is to use Java’s built-in Integer::parseInt method which takes a String argument and converts it to an int (line 10 in Fig. 2(b)). (Note that if the given argument is not a valid integer value, this method will throw an exception.) Now that the year has been manually and explicitly parsed from the initial date string into an integer value that can be incremented, the program compiles and prints the expected message, as shown in Fig. 2(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

 public static void main(String... args) {
   String date = LocalDate.now().toString(); // "2021-12-21"
   String year = date.split("-")[0]; // "2021"
   int newYear = year + 1;
   System.out.println("Happy New Year " + newYear + "!");
 }
}
IncompatibleTypesParsing.java:10: error: incompatible types: String cannot be converted to int
    int newYear = year + 1;
                       ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.time.LocalDate;

public class IncompatibleTypesParsing {

  public static void main(String... args) {
    String date = LocalDate.now().toString();
    String year = date.split("-")[0];
    int newYear = Integer.parseInt(year) + 1;
    System.out.println("Happy New Year " + newYear + "!");
  }
}
Happy New Year 2022!

Figure 2: Incompatible types when parsing (a) error and (b) resolution

 

Incorrect type assignments

Sometimes, the incompatible types error can occur due to basic negligence, where the only mistake is an accidental mis-declaration of a variable’s type (Fig. 3(a)). In these instances, the issue is quite obvious and simply correcting the type declaration solves the problem (Fig. 3(b)).

(a)

1
2
3
4
5
6
7
8
9
package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   int greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
IncompatibleTypesAssignment.java:6: error: incompatible types: String cannot be converted to int
    int greeting = "Merry Christmas!";
                   ^
1 error

(b)

1
2
3
4
5
6
7
8
9
package rollbar;

public class IncompatibleTypesAssignment {

 public static void main(String... args) {
   String greeting = "Merry Christmas!";
   System.out.println(greeting);
 }
}
Merry Christmas!

Figure 3: Incompatible types with incorrect assignment (a) error and (b) resolution

 

Incorrect method return types

A slightly less common but non-surprising occurence of the incompatible types error, especially when refactoring is involved, can be found in method return types. Namely, sometimes a method’s return statement ends up returning a value that doesn’t match the method’s declared return type (Fig. 4(a)). This issue has two possible remedies; either make the value returned match the return type (Fig. 4(b)), or change the method’s return type to match the actual value returned (Fig. 4(c)). And in the case of void methods (methods with no return type), one can simply get rid of the return statement if the return value is never used, as is the case with the example in Fig. 4.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
IncompatibleTypesReturn.java:11: error: incompatible types: unexpected return value
    return true;
           ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static void printGreeting() {
   System.out.println("Happy Holidays");
 }
}
Happy Holidays!

(c)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

public class IncompatibleTypesReturn {

 public static void main(String... args) {
   printGreeting();
 }

 static boolean printGreeting() {
   System.out.println("Happy Holidays");
   return true;
 }
}
Happy Holidays!

Figure 4: Incompatible types with incorrect return type (a) error and (b)(c) two solutions

 

Incorrect imports and similarly named reference types

It is not uncommon to come across classes or other reference types with the same or a similar name. In fact, this happens even within the standard Java API, and can baffle many programmers, beginners and experts alike. One such case is the List class which represents one of Java’s main collection data structures [6]. This reference type can easily come into collision with another type of the same name, but from a different package. Namely, that’s the java.awt.List class that is part of Java’s built-in AWT API for creating graphical user interfaces [7]. All it takes is accidentally importing the wrong package, and the compiler immediately complains about the type mismatch, raising the incompatible types error, as demonstrated in Fig. 5(a). Fixing the import on line 5, as shown in Fig. 5(b), sorts things out.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.awt.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
IncompatibleTypesList.java:10: error: incompatible types: ArrayList<String> cannot be converted to List
    List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
                 ^
1 error

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
package rollbar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IncompatibleTypesList {

 public static void main(String... args) {
   List songs = new ArrayList<String>(Arrays.asList("Silent Night", "Deck the Halls", "Jingle Bells", "Winter Wonderland"));
   System.out.println(songs);
 }
}
[Silent Night, Deck the Halls, Jingle Bells, Winter Wonderland]

Figure 5: Incompatible types incorrect reference type (a) error and (b) resolution

Popular external libraries are also prone to naming their reference types similarly, so whenever relying on such a library for a certain feature or functionality it is important to pick one, or be careful not to confuse one for another, if multiple libraries are already being used.

Fig. 6(a) shows an example of passing a JSON type object to a method as an argument. Here, the method printJson expects an argument of type JsonObject, but the calling method tries to pass in an instance of the similarly named JSONObject reference type, part of a different library altogether. This results in the incompatible types error being raised by the compiler, with the alert org.json.JSONObject cannot be converted to javax.json.JsonObject pointing to the erroneous method call. Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import org.json.JSONObject;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JsonObject json = Json.createObjectBuilder(jsonMap).build();

    printJson(json);
}

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
IncompatibleTypesJson.java:18: error: incompatible types: 
javax.json.JsonObject cannot be converted to org.json.JSONObject
    printJson(json);
              ^

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

import javax.json.Json;
import javax.json.JsonObject;
import java.util.Map;

public class IncompatibleTypesJson {

  public static void main(String... args) {
    Map<String, Object> jsonMap = Map.of(
        "name", "Saint Nicholas",
        "nicknames", new String[]{"Santa Claus", "Father Christmas"},
        "location", "North Pole"
    );

    JSONObject json = new JSONObject(jsonMap);

    printJson(json);
  }

  static void printJson(JSONObject jsonObject) {
    System.out.println(jsonObject.toString(4));
  }
}
{
    "name": "Saint Nicholas",
    "location": "North Pole",
    "nicknames": [
        "Santa Claus",
        "Father Christmas"
    ]
}

Figure 6: Incompatible types incorrect reference type (a) error and (b) resolution

Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4]. Depending on the specific compiler that is being used and its configuration settings, either of these errors could be triggered in this kind of scenario.

 

Summary

As a strongly typed language, Java has strict rules regarding data types and how they interoperate. These rules affect variable assignment, method invocation, return values, etc. This makes Java code verbose, but at the same time quite secure, as it allows for many errors to be detected during compilation. One such error is the incompatible types error, which is directly tied to Java’s type system. This article provides some background into Java types and dives into the symptoms and causes behind the incompatible types error, by presenting a series of relevant examples tailored to bring clarity in understanding and successfully managing this error.

 

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

 

References

[1] R. Liguori and P. Liguori, 2017. Java Pocket Guide, 4th ed. Sebastopol, CA: O'Reilly Media, pp. 23-46.

[2] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 18, 2021]

[3] D. Capka, 2021. Lesson 3 - Variables, type system and parsing in Java, Ictdemy.com. [Online]. Available: https://www.ictdemy.com/java/basics/variables-type-system-and-parsing-in-java. [Accessed: Dec. 19, 2021]

[4] Rollbar, 2021. How to Fix Method/Constructor X in Class Y Cannot be Applied to Given Types in Java, Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-fix-method-constructor-in-class-cannot-be-applied-to-given-types-in-java/. [Accessed: Dec. 21, 2021]

[5] W3schools.com, 2021. Java Type Casting. Refsnes Data. [Online]. Available: https://www.w3schools.com/java/java_type_casting.asp. [Accessed: Dec. 21, 2021]

[6] Oracle.com, 2021. Lesson: Implementations (The Java™ Tutorials > Collections). [Online]. Available: https://docs.oracle.com/javase/tutorial/collections/implementations/index.html. [Accessed: Dec. 21, 2021]

[7] Oracle.com, 2020. Package java.awt (Java SE 15 & JDK 15). Oracle and/or its affiliates [Online]. Available: https://docs.oracle.com/en/java/javase/15/docs/api/java.desktop/java/awt/package-summary.html. [Accessed: Dec. 21, 2021]

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape