Choose Your Language

Thursday, 25 April 2013

Simple Login Application Using JSP Servlets MySQL and Tomcat

index.jsp

<%--
    Document   : index
    Created on : 30 Dec, 2012, 10:39:52 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page language="java"  %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>       
        <form method="get" action="/AppContextPath/LoginServlet">
        <table>               
            <tr>
                <td></td>
                <td align="left">username</td>
                <td><input type="text" name="uname"/></td>
                <td></td>                               
            </tr>
            <tr>
                <td></td>
                <td align="left">password</td>
                <td><input type="password" name="upassword"/></td>
                <td></td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td><input type="submit" value="submit"></td>
                <td></td>
            </tr>
               
            </table>
        </form>
    </body>
</html>

UserBean.java
public class UserBean {
    private int uid;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }
   
     private String username;
     private String password;
     private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
     private String lastName;

    public boolean isValid() {
        return valid;
    }

    public void setValid(boolean valid) {
        this.valid = valid;
    }
     public boolean valid;
}


LoginServlet.java
 import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 public class LoginServlet extends HttpServlet {
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try{
            UserBean user=new UserBean();
            user.setUsername(request.getParameter("uname"));
            user.setPassword(request.getParameter("upassword"));
            user=UserDAO.login(user);
          
            if(user.isValid()){
                HttpSession session=request.getSession(true);
                session.setAttribute("currentSessionUser", user);
                response.sendRedirect("userLogged.jsp");               
            }
            else{
                response.sendRedirect("index.jsp");
            }
        }
        catch(Throwable  theException){
            System.out.println("Exception is"+theException);
           
        }    
    }
}

ConnectionManager.java
import java.sql.*;
import java.util.*;
/**
 *
 * @author Aravind Sankaran
 */
public class ConnectionManager {
    static Connection con;
    static String url="jdbc:mysql://localhost:3306/databasename?";
    static String userName = "dbusername";
    static String password = "dbpassword";
   
    public static Connection getConnection() {
    try {
       Class.forName("com.mysql.jdbc.Driver");
                try {
                con = DriverManager.getConnection(url,userName,password);
                System.out.println("connection success");
                }
            catch(SQLException ex){
                System.out.println(ex);
                 }
        }
    catch(ClassNotFoundException e){
        System.out.println(e);
         //e.printStackTrace();
        }
    return con;
    }
}

UserDAO .java 

public class UserDAO {
 static Connection currentConnection = null;
    static ResultSet rs = null;
    static PreparedStatement preparedStatement = null;
    static PreparedStatement preparedStatement1 = null;
    public static UserBean login(UserBean bean){
        Statement statement=null;   
        String userName=bean.getUsername();
        String userPassword=bean.getPassword();
        String searchQuery="select * from usertable where username='"+userName+"' AND password='"+userPassword+"'";
        System.out.println("before getting connection your given user name is"+userName);
        System.out.println("before getting connection your given user password is"+userPassword);
        System.out.println("your searchQuery is"+searchQuery);
        try{
            currentConnection=ConnectionManager.getConnection();
            statement=currentConnection.createStatement();
            rs=statement.executeQuery(searchQuery);
            boolean more=rs.next();
            if(!more){
                System.out.println("not a registered user");
                bean.setValid(false);;
            }
            else if(more){
                String firstName=rs.getString("firstname");
                String lastName=rs.getString("lastname");
                System.out.println("welcome "+firstName+" "+lastName+"");               
                bean.setFirstName(firstName);
                bean.setLastName(lastName);
                bean.setValid(true);
            }
           
        }
        catch(Exception ex){
            System.out.println("login failed"+ex);
            }
        finally{
            if(rs!=null){
                try{
                    rs.close();
                    }
                catch(Exception e){}                  
                rs=null;
            }
            if(statement!=null){
                try{
                    statement.close();
                }
                catch(Exception e){}
                statement=null;
            }
            if(currentConnection!=null){
                try{
                    currentConnection.close();
                }
                catch(Exception e){}
                currentConnection=null;
            }
        }
        return bean;
    }
}

userLogged.jsp
<%--
    Document   : userLogged
    Created on : 19 Aug, 2012, 11:50:16 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8" import="packagename.UserBean"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> User Logged Successfully</title>
    </head>
    <body>
          <table align="center">
            <%UserBean currentUser=((UserBean)(session.getAttribute("currentSessionUser")));%>              
            <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td><font size="3"><b>Welcome</b></font></td>
                <td><font size="3"><b><%=currentUser.getFirstName()+" "+currentUser.getLastName()%></b></font></td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        <%@ include file="footer.jsp"%>
    </body>
</html>

footer.jsp
<%--
    Document   : footer
    Created on : 19 Aug, 2012, 11:50:16 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
this is my footer
</html>

Table Structure of usertable

+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| firstname  | varchar(25) | YES  |     | NULL    |       |
| lastname  | varchar(25) | YES  |     | NULL    |       |
| username | varchar(25) | YES  |     | NULL    |       |
| password | varchar(25) | YES  |     | NULL    |       |
+-----------+-------------+------+-----+---------+-------+

jar file needed
mysql-connector-java-3.1.14-bin








How to set path of JDK in Windows

path is required for using tools such as javac, java etc. if you are going to save java files inside jdk/bin folder, not need to set path. but if you are going to save your java file outside jdk/bin folder, path setting is necessary.
Two ways we can set path of JDK.
1. Temporary
2. Permanent

Setting Temporary Path of JDK in Windows
For setting Temporary path, need to follow these steps
1. open command prompt
2. copy path upto bin folder of jdk
3. write in command prompt sett path=copied path

Example:
E:\study>set path=C:\Program Files\Java\jdk1.6.0_26\bin;


Setting Permanent Path of JDK in Windows
 For setting Permanent path, need to follow these steps
1. Go to My Computer properties
2. Advanced System Settings
3. Environment variables
4. Select path from System variables
5. Click Edit
6. Give path of JDK upto bin folder as variable value
7. Press Ok.
8. Press Ok.
9. Press Ok.



Sunday, 14 April 2013

Barcode generation using servlets

BarcodeServlet.java
 
import com.onbarcode.barcode.Code128;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Aravind Sankaran
 */
public class BarcodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String number="";
            try {
            Code128 barcode = new Code128();            
            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 1; ++idx){
            long randomInt = randomGenerator.nextInt(01234567);           
            number=String.valueOf(randomInt);
            }
            System.out.println("random number generated is"+number);
            barcode.setData(number);                            
            ServletOutputStream servletoutputstream = response.getOutputStream();
             
            response.setContentType("image/jpeg");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
          
            // Generate Code-128 barcode & output to ServletOutputStream
            barcode.drawBarcode(servletoutputstream);
     
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}
jar file needed:
barcode.jar

Collection Framework Diagram

collection framework

exception hierarchy diagram in java

exception hierarchy

Generate PDF using Servlets

GeneratePDF.java

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GeneratePDF extends HttpServlet {
    Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);
    Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD);    
    Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.NORMAL, BaseColor.RED);
    Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,Font.BOLD);
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String file="E:\\AravindSankaran.pdf";
       try {
            Document document = new Document();
            PdfWriter.getInstance(document,new FileOutputStream(file) );

            document.open();
                        addMetaData(document);
                        addTitlePage(document);
                        addContent(document);
                        document.getPageNumber();
            document.close();
          
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
public void addMetaData(Document document){
    document.addTitle("My Profile");
    document.addSubject("using i text");
    document.addKeywords("java j2ee soa bpel");
    document.addAuthor("aravind");
    document.addCreator("aravind sankarran");
}
public void addTitlePage(Document document){
    
    Paragraph preface=new Paragraph();
    addEmptyLine(preface, 1);
   
    preface.add(new Paragraph("Title of the document",catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Report generated by"+System.getProperty("user.name")+""+new   Date(),smallBold));
   

    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This document describes something which is very important ",
        smallBold));
   
    addEmptyLine(preface, 8);

    preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
        redFont));
        try {
            document.add(preface);
            document.getPageNumber();
            document.newPage();
        } catch (DocumentException ex) {
            Logger.getLogger(GeneratePDF.class.getName()).log(Level.SEVERE, null, ex);
        }
}
public  void addContent(Document document) throws DocumentException{
    Anchor anchor = new Anchor("First Chapter", catFont);
    anchor.setName("First Chapter");
    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Subcategory 1", subFont);
    Section subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Hello"));

    subPara = new Paragraph("Subcategory 2", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("Paragraph 1"));
    subCatPart.add(new Paragraph("Paragraph 2"));
    subCatPart.add(new Paragraph("Paragraph 3"));

    createList(subCatPart);
    Paragraph paragraph = new Paragraph();
    addEmptyLine(paragraph, 5);
    subCatPart.add(paragraph);

    createTable(subCatPart);

    document.add(catPart);

    anchor = new Anchor("Second Chapter", catFont);
    anchor.setName("Second Chapter");

    catPart = new Chapter(new Paragraph(anchor), 1);

    subPara = new Paragraph("Subcategory", subFont);
    subCatPart = catPart.addSection(subPara);
    subCatPart.add(new Paragraph("This is a very important message"));

    document.add(catPart);
}
public void createTable(Section subCatPart)
      throws BadElementException {
    PdfPTable table = new PdfPTable(3);

    PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Table Header 2"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Table Header 3"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);

    table.addCell(c1);
    table.setHeaderRows(1);
    table.addCell("1.0");
    table.addCell("1.1");
    table.addCell("1.2");
    table.addCell("2.1");
    table.addCell("2.2");
    table.addCell("2.3");
    subCatPart.add(table);
}
public void createList(Section subCatPart) {
    List list = new List(true, false, 10);
    list.add(new ListItem("First point"));
    list.add(new ListItem("Second point"));
    list.add(new ListItem("Third point"));
    subCatPart.add(list);
  }
public void addEmptyLine(Paragraph paragraph,int number){
    for(int i=0;i<number;i++){
        paragraph.add(new Paragraph(" "));
       
    }
}
}
jar file needed:
itextpdf-5.2.1.jar

web application to send mail using jsp and servlet

sendmail.jsp
<%--
    Document   : sendmail
    Created on : 10 Apr, 2013, 8:49:08 PM
    Author     : Aravind Sankaran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="post" action="/applicationcontext/MailSender">
                                <table>
                                    <tr>
                                        <td></td>
                                        <td>gmail Id</td>
                                        <td><input type="text" name="gmailId" style="width: 418px"></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>gmail Password</td>
                                        <td>

                                        <input type="password" name="gmailPassword" style="width:  418px"></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>To</td>
                                        <td><input type="text" name="to" style="width: 418px"></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>Subject</td>
                                        <td><input type="text" name="subject" style="width: 418px"></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td>Body</td>
                                        <td><textarea rows="3" cols="50" name="body"></textarea></td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>&nbsp;</td>
                                        <td>&nbsp;</td>
                                        <td align="center"><input type="submit" value="Send Mail"></td>
                                        <td></td>
                                    </tr>
                                </table>
                                </form>

    </body>
</html>

MailSender.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commons;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Aravind Sankaran
 */
public class MailSender extends HttpServlet {

   
    private static final String SMTP_HOST_NAME = "smtp.gmail.com"; 
    private static final String SMTP_PORT = "465"; 
    final  String password="";
     final String from="";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }



    @Override

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {               

        
         String gmailId = request.getParameter("gmailId");

         String gmailPassword=request.getParameter("gmailPassword");
         String toEmailAddress = request.getParameter("to");

         String toEmail[]={toEmailAddress};
         String emailSubject = request.getParameter("subject");

         String emailBody =request.getParameter("body");
         MailSender mailer=new MailSender();
        try {
            mailer.sendSSLMessage(toEmail, emailSubject,emailBody , gmailId, gmailPassword);
        } catch (MessagingException ex) {
            Logger.getLogger(MailSender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

public void sendSSLMessage(String recipients[], String subject, 
            String message, final String from, final String password) throws MessagingException

        boolean debug = true; 
        Properties props = new Properties(); 
        props.put("mail.smtp.host", SMTP_HOST_NAME); 
        props.put("mail.smtp.auth", "true"); 
        props.put("mail.debug", "true"); 
        props.put("mail.smtp.port", SMTP_PORT); 
        props.put("mail.smtp.socketFactory.port", SMTP_PORT); 
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY); 
        props.put("mail.smtp.socketFactory.fallback", "false"); 
 
        Session session = Session.getDefaultInstance(props, 
                new javax.mail.Authenticator() { 
                    protected PasswordAuthentication getPasswordAuthentication() { 
                        return new PasswordAuthentication(from, 
                                password); 
                    } 
                });
 
        session.setDebug(debug); 
 
        Message msg = new MimeMessage(session); 
        InternetAddress addressFrom = new InternetAddress(from); 
        msg.setFrom(addressFrom); 
 
        InternetAddress[] addressTo = new InternetAddress[recipients.length]; 
        for (int i = 0; i < recipients.length; i++) { 
            addressTo[i] = new InternetAddress(recipients[i]); 
        } 
        msg.setRecipients(Message.RecipientType.TO, addressTo); 
 
        msg.setSubject(subject); 
        msg.setContent(message, "text/plain"); 
        Transport.send(msg); 
    } 

 
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

 

web.xml
<web-app>
<servlet>
        <servlet-name>MailSender</servlet-name>
        <servlet-class>commons.MailSender</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>MailSender</servlet-name>
        <url-pattern>/MailSender</url-pattern>
</servlet-mapping>
<session-config>
        <session-timeout>
            30
        </session-timeout>
</session-config>
<welcome-file-list>
        <welcome-file>sendmail.jsp</welcome-file>
</welcome-file-list>
</web-app>

jar file needed:
java-mail-1.4.4.jar





Thursday, 4 April 2013

program to reverse a string

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StringReverse {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
         String original, reverse = "";
         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
          try {
              System.out.println("Enter a string to reverse");
            original = br.readLine();           
            int length=original.length();
               for ( int i = length - 1 ; i >= 0 ; i-- )
                 reverse = reverse + original.charAt(i);
       
                   System.out.println("Reverse of entered string is: "+reverse);
              
           
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
         
       }   

}

output:
Enter a string to reverse
aravind sankaran
Reverse of entered string is: naraknas dnivara

Program to print Diamond shape

public class Diamond {

    public static void main(String[] args) {
        for (int i = 1; i < 10; i += 2) {
          for (int j = 0; j < 10 - i / 2; j++)
            System.out.print(" ");

          for (int j = 0; j < i; j++)
            System.out.print("*");

          System.out.print("\n");
        }

        for (int i = 7; i > 0; i -= 2) {
          for (int j = 0; j < 10 - i / 2; j++)
            System.out.print(" ");

          for (int j = 0; j < i; j++)
            System.out.print("*");

          System.out.print("\n");
        }
   
      }
    }

output:

           *
         ***
        *****
       *******
      *********
       *******
        *****
          ***
           *

Simple Calculator Program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SimpleCalculator {
public static void main(String a[]) {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.print("enter first value");       
        int firstValue=Integer.parseInt(br.readLine());

        System.out.print("enter second value");
        int secondValue=Integer.parseInt(br.readLine());

        int result;

        System.out.println("select any one operation");
        System.out.println("+ - * /");
        char op=(char)br.read();

        if(op=='+'){
            result=firstValue+secondValue;
            System.out.println("selected addition operation and the result is "+result);
        }
        else if(op=='-'){
            result=firstValue-secondValue;
            System.out.println("selected subtraction operation and the result is "+result);
        }
        else if(op=='*'){
            result=firstValue*secondValue;
            System.out.println("selected multiplication operation and the result is "+result);
        }
        else if(op=='/'){
            result=firstValue/secondValue;
            System.out.println("selected division operation and the result is "+result);
        }
       
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

output:
enter first value3
enter second value4
select any one operation
+ - * /
*
selected operation is multiplication and the result is 12

Try Catch Finally Scenario's

try catch finally block
Syntax:
 try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        statements;
    }

Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        statements;
    }
}
}

Scenario's
1. try catch finally inside try block
Example:
public class TryCatchFinally {
void display(){
    try{
        try{
              statements;
             }catch (Exception e) {
                 // TODO: handle exception
             }finally{
                    statements;
             }

         }catch (Exception e) {
        // TODO: handle exception
         }finally{
        statements;
         }
  }
}

2. try catch inside catch block
Example:
try{
        statements;
    }catch (Exception e) {
     try{
        statements;
          }catch (Exception e) {
        // TODO: handle exception
          }

        // TODO: handle exception
    }finally{
        statements;
    }

 3. try catch inside finally block
Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (Exception e) {
        // TODO: handle exception
    }finally{
        try{
          statements; 
        }catch (Exception e) {
            // TODO: handle exception
        }  
 
    }
}
}

4. try and finally without catch block
Example:
public class TryCatchFinally {
void display(){
    try{
          statements;
    }finally{
          statements; 
    }
}
}

5. try and multiple catch block
Example:
public class TryCatchFinally {
void display(){
    try{
        statements;
    }catch (NullPointerException e) {
        // TODO: handle exception
    }catch (Exception e) {
        // TODO: handle exception
    }
finally{
         statements;  
    }   
}
}

Looping Control structure

Control structure includes the looping control structure and conditional or branching control structure. 
In a looping control structure, series of statements are repeated.

looping control structure

for loop
Syntax:
for(intial value;condition;increment or decrement){
Statements;


Example:
Class ForLoop{
public static void main(String a[]){
for(int i=0;i<3;i++){
System.out.println(i);


output:
0
1
2
 
while loop
Syntax:
while (condition){
Statements;
}

Example:
Class While Loop{
public static void main(String a[]){
int i=0;
while (i<3){
System.out.println(i);
i++;


output:
0
1
2


do..while loop 
Syntax:
do{
Statements;

while(condition);

Example

Class DoWhileLoop{
public static void main(String a[]){
int i=0;
do{
 System.out.println(i); 
i++
}
while (i<3)

output:
0
1
2