JSP | Declaration Tag (original) (raw)
Last Updated : 14 May, 2026
The Declaration Tag in JSP is used to declare variables, methods, and classes in a JSP page. The code written inside this tag is placed outside the _jspService() method by the JSP container, making it available throughout the JSP page.
- Uses <%! %> syntax to declare variables, methods, and classes
- Declarations become class-level members of the generated servlet
- Used for defining reusable logic, not for direct output
**Syntax:
<%! declaration code %>
**Example: JSP Declaration Tag which initializes a string
HTML `
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
GeeksforGeeks <%! String username="Geeks"; %><%="Hello : "+username %>
`
**Output:

output
**Explanation:
- <%! String username = "Geeks"; %> → Declares a class-level variable named username
- This variable is stored outside _jspService(), so it is accessible throughout the JSP
- <%= "Hello: " + username %> → Uses Expression Tag to display the value on browser
**Example : JSP Declaration Tag which initializes a method
HTML `
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
GeeksforGeeks <%! int factorial(int n) { if (n == 0) return 1; return n*factorial(n-1); } %> <%= "Factorial of 5 is:"+factorial(5) %>`
**Output

Output
**Explanation:
- <%! int factorial(int n) { ... } %> -> Declares a method inside JSP
- The method is part of the generated servlet class and can be reused
- return n * factorial(n - 1) -> Uses recursion to calculate factorial
- <%= factorial(5) %> -> Calls the method and prints result using Expression Tag