JSP program to check leap year or not

Here is another JSP program to check leap year, you will learn the below JSP tricks from this program:

1. Retrieve the value from HTML form in JSP.
2. Check if the entered value is numeric in JSP.
3. Convert string to integer in JSP.
4. Using multiple IF Conditions in JSP.

JSP script to find leap year:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Program to find Leap year</title>
    </head>
    <body>
    <h2>JSP Program to check Leap year or not - Script by <a href="http://www.tutorialsmade.com/">Tutorialsmade.com</a></h2>
    <form action="" method="post">
        <input type="text" name="year" />
        <input type="submit" />
    </form>
    </body>
</html>
<%
    //check if post request
    if("POST".equalsIgnoreCase(request.getMethod()))
    {
        //define variables
        String year;
        int yearint;
        Boolean isnum;
        //get the entered year from text box 
        year = request.getParameter("year");
        //check if entered is a number
        isnum = year.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+");
        
        //if it is number then allow
        if(isnum)
        {
            //change string to int
            yearint = Integer.parseInt(year);
            
            //three conditions to find out the leap year
            if( (0 == yearint % 4) && (0 != yearint % 100) || (0 == yearint % 400) )
            {
                out.print("<p>"+year+" is a leap year");  
            }
            else
            {
                out.print("<p>"+year+" is not a leap year");  
            }
        }else{
           out.println("<p>Please enter numbers only</p>");
        }
        
    }
%>

The code is self explanatory, read the comments in the script. This is a single page JSP web application, not a JSP & Servlet web application.

To find the leap year, these are the conditions,

1. Year should be evenly divisible by 4 (year % 4 == 0)
2. AND (&&) Year should not be evenly divisible by 100 (year % 100 != 0)
3. OR (||) year should be evenly divisible by 400 (Year % 400 == 0)

if both the 1st AND 2nd condition is true OR 3rd is true then it is a Leap year.

Enjoy learning. Good luck.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top