Unveiling the Mystery Behind "'void' type not allowed here" Error
Encountering the "void type not allowed here" error can be puzzling. To understand its significance, let's delve into its context.
Consider the code snippet below:
class obj { public static void printPoint(Point p) { System.out.println("(" + p.x + ", " + p.y + ")"); } public static void main(String[] arg) { Point blank = new Point(3, 4); // This line generates the error System.out.println(printPoint(blank)); } }
Upon attempting to compile this code, you encounter the error message:
obj.java:12: 'void' type not allowed here System.out.println(printPoint(blank)); ^ 1 error
What Went Wrong?
The root of the error lies in the printPoint method. Its declaration specifies that it returns void, meaning it does not return any value. Consequently, the main method's attempt to print the return value of printPoint (which is void) results in the "void type not allowed here" error.
What Does the Error Message Mean?
The error message clearly indicates that the return type of a method determines what can be done with its return value. In this case, since the printPoint method returns void, its return value cannot be printed using System.out.println().
The Solution
To rectify this issue, you need to modify your code to eliminate the unnecessary printing of the printPoint return value. Instead, you should directly call the printPoint method as follows:
printPoint(blank);
This will eliminate the type mismatch and allow the code to compile and execute correctly.
The above is the detailed content of Why Does Java Throw a ''void' Type Not Allowed Here' Error?. For more information, please follow other related articles on the PHP Chinese website!