What Does "Incompatible Types: Void Cannot Be Converted to ..." Mean

What does Incompatible types: void cannot be converted to ... mean?

Quick answer

The compiler is telling you that your code is trying to use the "result" of a method that doesn't return a result.

Solution:

  1. Read the javadoc for the method you are trying to call (or the source code if you don't have javadocs).

  2. From the javadocs (or source code), work out how the method should really be used.

  3. Correct your code to either not use the (non-existent) result, or to use a different method. Alternatively, if it is one of your methods that you are calling, another possible correction might be to change the method to return an appropriate value.

Detailed example

Consider this example:

public class Test {
private static void add(int a, int b) {
int res = a + b;
}

public static void main(String[] args) {
int sum = add(1, 1);
}
}

When I compile this using javac (Java 8), I get the following compilation error.

$ javac Test.java 
Test.java:7: error: incompatible types: void cannot be converted to int
int sum = add(1, 1);
^
1 error

The compilation error is actually telling us a few things:

  • The compiler has detected a problem at the indicated position on the indicated line in the main method. The root cause of the problem is not necessarily on that line, but that is where the compiler has figured out that something is wrong.

  • It is a type error - hence the "incompatible types" phrase.

  • The incompatibility involves two types: void and int.

  • The compiler thinks that the code requires a conversion from void to int ... and that is not possible.



So what is this void type?

Well, you will most likely have learned that Java supports two kinds of type: primitive types and reference types. The void type is not either of these. It is the "type" that means "there is no value". (If you consider types to be sets of values, then void is the empty set.)

The primary use for the void type is used is in method declarations. Look at the declaration of the add method above. Notice that we have declared add with the signature:

private static void add(int a, int b)

That signature states that the add method takes two int methods, and returns void. That means that the method will return nothing.

Yet ... we have called it like this:

int sum = add(1, 1);

This is expecting the add call to return an int value that we will assign to sum.

This is what the "void cannot be assigned to ..." error message really means. The compiler is telling us that code is trying to use the result of a method that has been declared to return no result. That's not possible. The Java language does not allow you to "pull a value out of the air" to use.


There are potentially two ways to make the compilation error go away:

  1. We could change the declaration of the method so that it does return a value. For example:

    private static int add(int a, int b) {
    int res = a + b;
    return res;
    }
  2. We could change the call site so that it does not attempt yo use the (non-existent) return value. For example:

    add(1, 1);

In this example, either approach would do that. But only one approach (the first one) makes the code work as intended.

incompatible types: void cannot be converted to int

Your program does not have to return an int in public static int main. Instead you can have it as void (meaning don't return anything). You should simply just print your statements and don't return them. Also the int[] should be String[] and Scanner should check for nextInt() as pointed out in comments!

import java.util.InputMismatchException;
import java.util.Scanner; // This will import just the Scanner class.

public class GuessAge {
public static void main(String[] args) {
System.out.println("\nWhat is David's Age?");
Scanner userInputScanner = new Scanner(System.in);
int age = userInputScanner.nextInt();



int validInput = 20;

// typo in your code - compare to age
if (validInput == age) {
System.out.println("Correct!!");
}
else {
System.out.println("Wrong....");
}
}

}

Forcing something to be destructed last in C++

You could use the Observer pattern. A Controller communicates to it's supervisor that it's being destroyed. And the Supervisor communicates the same to it's child upon destruction.

Take a look at http://en.wikipedia.org/wiki/Observer_pattern

Java error: void cannot be converted to String

Your function has no return value void and you try to assign it to a string variable, that is what the error message means.

So change:

public static void encrypt(String original) throws Exception {

to

public static String encrypt(String original) throws Exception {

and

return sb.toString()

So the class looks like:

class MD5Digest {
public static String encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}

System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
return sb.toString();
}

}

BTW: Take care of Java's naming convention. Class names should be subjects.

EDIT:

Because your encrypt message throws an exception, you have to throw the exception also in public static void main(String []args) throws Exception{ or you have to handle it in a try-catch-block

error: incompatible types: void cannot be converted to double

System.out.print() returns no value; it has a return type of void.

In order to rewrite this without any errors, change it to something like this:

public static void generateReport(double sqft,  double gallonCost, int numGallons, double hoursLabor, double paintCost, double laborCost, double totalCost) {
System.out.print("To paint" + sqft + "square feet, with");
System.out.print("paint that costs" + gallonCost + "per gallon,");
System.out.print("you will need" + numGallons + "gallons of paint");
System.out.print("and" + hoursLabor + "hours of labor.");
System.out.print("The cost of the paint is: " + paintCost );
System.out.print("The cost of the labor is: "+ laborCost);
System.out.print("The total cost of the job is: " + totalCost);
System.out.println();


Related Topics



Leave a reply



Submit