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
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>
<!--declaration of username variable.... -->
<%! String username="Geeks"; %>
<!--In expression tag a string is initialised as Geeks -->
<%="Hello : "+username %>
<!-- Displaying expression using Expression Tag -->
</body>
</html>
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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>
<html>
<body>
<%!
int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
}
%>
<%= "Factorial of 5 is:"+factorial(5) %>
</body>
</html>
</body>
</html>
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