Search code examples
jspjsp-tags

why void method cannot print inside of scriptlets and expression tags in jsp



When I try to print a method that return int using declaration tag usually scriplets and expression tags can print that method.

        <%! int print(int i, int j, int k) {
                return i + j + k;
        }%>

        <%= print(10, 20, 30)%> 
        <% out.print(print(10, 20, 300));%>

But when I try to print a void return method in using same tags I get a compilation error.

    <%! void print(int i, int j, int k) {
            System.out.print(i + j + k);
        }%>

    <%= print(10, 20, 30)%> 
    <% print(10, 20, 300);%>

..

C:\Users\dilin\Documents\NetBeansProjects\Practice\build\generated\src\org\apache\jsp\index_jsp.java:60: error: 'void' type not allowed here
  out.print( print(10, 20, 30));
                  ^1 error

Is this because void methods cannot give as a print output?


I'm new to web web development. So please bear with me. Thank you.


Solution

  • This is plain and simple. In your scriptlet, you are calling java.io.PrintStream#print method with no argument. Threrefore, the compiler gives you an error.

    Refer to the Java docs. While there are several overloaded variants of print method in PrintStream, none of them is a no-argument overload. Your custom print method returns void and hence you can't pass it to a method that accepts an argument.

    On a side note, use of scriptlets is highly discouraged because they can make your application vulnerable to security threats.