Java Servlet Factorial Program Using Recursion

Java Servlet Factorial Program Using Recursion

Posted in : Java Posted on : October 11, 2011 at 7:04 PM Comments : [ 0 ]

In this section you will learn how to find the factorial of a number.

Java Servlet Factorial Program Using Recursion

In this section you will learn how to find the factorial of a number.

Here I am giving a simple java servlet example which is concern for finding the factorial of a number. In mathematics factorial is defined as n! = n*(n-1)...2*1.  where, n is a natural number and n ≥ 1. Value of 0! is 1. for example 5! = 5*4*3*2*1.

Now, since I have to use this function in java servlet program, therefore I have created a java servlet class named FactorialServlet which extends the HttpServlet class. In the body of class I overridden the method doGet() and created an objects of HttpServletRequest and HttpServletResponse into its parameter. Inside the doGet() method first I set the mime type that in which format the browser will show the output. In the next line I used the getWriter() method of ServletResponse interface with the object of HttpServletResponse. HttpServletResponse interface extends this method from the ServletResponse. In Next step I am taking input using the getParameter() method of ServletRequest with the object of HttpServletRequest. And create a recursive method for manipulating factorial.

Example :


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<form method="get" action="factorialServlet">
<tr><td>Enter a value to find its factorial</td><td><input type="text" name="text1"/></td></tr>
<tr><td></td><td><input type="submit" value="ok"/></td></tr>

package simpleServletExample;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FactorialServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("text1"));


long fact(long a) {
if (a <= 1)
return 1;
else {
a = a * fact(a - 1);
return a;


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="" xmlns:xsi="" xsi:schemaLocation="">



Output :

When you will execute the above example you will get the output as :

When you will enter the value

You will get the output like as :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics