Home > Java > javaTutorial > Why Does Java Throw a ''void' Type Not Allowed Here' Error?

Why Does Java Throw a ''void' Type Not Allowed Here' Error?

Mary-Kate Olsen
Release: 2024-11-17 13:33:01
Original
1072 people have browsed it

Why Does Java Throw a

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));
    }
}
Copy after login

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
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template