JSP Control Statements
There are various standard programming languages like C, C++, Java etc. that supports control statements. On the basis of that, JSP also follows the same methodology. Let's study the flow of control statements in Java Server Pages. Here, are some conditional statements about which we will discuss: -
- if else
- for loop
- while loop
- switch
IF...ELSE
JSP allows to use IF ELSE conditional statement as a programming logic of scriptlet tag. Apart from that, IF can also be used in many other ways like nested IF or standalone IF. Here is a simple example of IF ELSE statement.
index.jsp
<html> <head> <title>Tutorial and Example</title> </head> <body> <%! int num=8; %> <% if(num%2==0) { out.println("Number is even"); } else { out.println("Number is odd"); } %> </body> </html>
For Loop
Here, is a simple example of for loop.
<html> <head> <title>Tutorial and Example</title> </head> <body> <% for(int i=0;i<5;i++) { for(int j=1;j<=i+1;j++) { out.print(j); } out.print("<br>"); } %> </body> </html>
While loop
Here, is a simple example of while loop.
<html> <head> <title>Tutorial and Example</title> </head> <body> <% int i=0; while(i<4) { i++; out.print(i+"<br>"); } %> </body> </html>
Switch Statement
Switch is used to maintain the flow of control statement. It contains various cases with one default case. The default case will execute only once, when none other case satisfies the condition. Here, is a simple example of switch statement.
index.jsp
<html> <head> <title>Tutorial and Example</title> </head> <body> <%! int weekday=4; %> <% switch(weekday) { case 1: out.print("Monday"); break; case 2: out.print("Tuesday"); break; case 3: out.print("Wednesday"); break; case 4: out.print("Thursday"); break; case 5: out.print("Friday"); break; case 6: out.print("Saturday"); break; default: out.print("Sunday"); break; } %> </body> </html>