Home > Java > javaTutorial > Why Does Java Throw a ''void' Type Not Allowed Here' Error When Trying to Print a Void Method's Result?

Why Does Java Throw a ''void' Type Not Allowed Here' Error When Trying to Print a Void Method's Result?

Mary-Kate Olsen
Release: 2024-11-10 22:20:03
Original
244 people have browsed it

Why Does Java Throw a

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

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

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!

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