Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes "'void' type not allowed here" error

Tags:

java

When I try to compile this:

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)) ;
        }
    }

I get this error:

obj.java:12: 'void' type not allowed here
        System.out.println (printPoint (blank)) ; 
                                               ^
1 error

I don't really know how to start asking about this other than to ask:

  • What went wrong here?
  • What does this error message mean?
like image 516
David Avatar asked Mar 14 '10 15:03

David


People also ask

What does it mean void type not allowed here?

When we run the code, the output throws an error, void type not allowed here . It happens because printMessage1() already has a print statement that prints the value , and it doesn't return anything when we call the function in a print statement; there's nothing to print in the main method.

What is a void type in Java?

Definition and Usage The void keyword specifies that a method should not have a return value.

What is meaning of return data type void?

A void return type simply means nothing is returned. System. out. println does not return anything as it simply prints out the string passed to it as a parameter.

What is void used for in Java?

It is a keyword and is used to specify that a method doesn't return anything. As the main() method doesn't return anything, its return type is void. As soon as the main() method terminates, the java program terminates too.


2 Answers

If a method returns void then there is nothing to print, hence this error message. Since printPoint already prints data to the console, you should just call it directly:

printPoint (blank); 
like image 175
Justin Ethier Avatar answered Oct 15 '22 10:10

Justin Ethier


You are trying to print the result of printPoint which doesn't return anything. You will need to change your code to do either of these two things:

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) ; 
        printPoint (blank) ;
    }
}

or this:

class obj
{
    public static String printPoint (Point p) 
    { 
        return "(" + p.x + ", " + p.y + ")"; 
    }
    public static void main (String[]arg)
    {
        Point blank = new Point (3,4) ; 
        System.out.println (printPoint (blank)) ;
    }
}
like image 36
Andrew Hare Avatar answered Oct 15 '22 09:10

Andrew Hare