Bright Java Tutorial

is brought to you by DoITBright LLC

JSP

If Else If Else Statement

As we have learned from our previous lesson that JSP or Java Server Pages is a Java technology used specifically as a server side application, most of it's programming syntax is Java. This is the main reason why it is best to learn Core Java programming before trying to learn Java Server Pages. The if - else if - else statement syntax is exactly the same with Java. This should be no surprise. Let us look at an example.

  <html>
    <head>
      <title>
        If Else If Else Statement In JSP
      </title>
    </head>
    <body>
  <%
    long longVar = 123;
    int intVar = 123;
    //let us try comparing 2 numeric values
    if(longVar == intVar) {
  %>
      The values of longVar and intVar are equal.
      <br/>
  <%
    } else {
  %>
      The values of longVar and intVar not are equal.
      <br/>
  <%
    }
    String stringVar1 = "ABC";
    String stringVar2 = "abc";
    //let us try comparing Strings
    if(stringVar1.equals(stringVar2)) {
  %>
      The values of stringVar1 and stringVar2 are equal.
      <br/>
  <%
    } else if(stringVar1.equalsIgnoreCase(stringVar2)) {
  %>
      The values of stringVar1 and stringVar2 are equal 
        but with different lower and upper case letters.
      <br/>
  <%
    } else {
  %>
      The values of stringVar1 and stringVar2 
        are not equal.<br/>
  <%
    }
  %>
    </body>
  </html>
                            

In the first part of the code, there is an opening scriptlet '<%' followed by 2 declaration of numeric variables with the same value of '123'. The next line is an 'if' condition. Then, after that, there is a closing scriptlet '%>'. We closed the scriptlet because we want to let JSP interpret the next lines of code to be part of the generated HTML code. After few lines of HTML code, we can find again an opening scriptlet '<%' followed by the right curly brace '}' to close the 'if' statement. Same principle applies to the 'else' condition. In the example provided, the values of the variables longVar and intVar are equal. Thus, the 'if' condition is satisfied.

In this tutorial, we have learned that writing if - else if - else statements in Java Server Pages or JSP is the same way we write it in Java. All we need to remember is, whenever we are writing Java lines of code, it should be enclosed by '<%' and '%>'.


Back