Understanding the "'void' Type Not Allowed Here" Error
When attempting to compile code involving methods, you may encounter the error "'void' type not allowed here." This error stems from a misunderstanding of how methods and void types interact.
The Void Type Explained
In Java, methods can have different return types, including void. A void method does not return any value and simply performs actions. In contrast, methods with a non-void return type (such as int, String, or Point) produce a value that can be assigned to a variable or used in an expression.
The Error Context
Consider the following code snippet:
import java.awt.*; 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); System.out.println(printPoint(blank)); } }
Here, an attempt is made to print the result of the printPoint method call. However, the printPoint method is defined as void, meaning it doesn't return any value. As a result, the line attempting to print the result (System.out.println(printPoint(blank))) will trigger the "'void' type not allowed here" error.
Resolving the Error
To resolve this error, you should remove the attempt to print the result of the printPoint method. Instead, simply call the method directly:
printPoint(blank);
By calling the printPoint method without attempting to assign its result to a variable or use it in an expression, you avoid the incorrect usage of the void type.
The above is the detailed content of Why Does Java Throw a ''void' Type Not Allowed Here' Error When Trying to Print a Void Method's Result?. For more information, please follow other related articles on the PHP Chinese website!