JBA

Practical1-A

A.1-Constructor Overloading
public class Student {  
//instance variables of the class  
int id;  
String name;  
  
Student(){  
System.out.println("this a default constructor");  
}  
  
Student(int i, String n){  
id = i;  
name = n;  
}  
  
public static void main(String[] args) {  
//object creation  
Student s = new Student();  
System.out.println("\nDefault Constructor values: \n");  
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);  
  
System.out.println("\nParameterized Constructor values: \n");  
Student student = new Student(10, "David");  
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);  
}  
}  
sdaDDSAD
A.2-MethoD Overloading
class Adder{  
static int add(int a,int b){return a+b;}  
static int add(int a,int b,int c){return a+b+c;}  
}  
class TestOverloading1{  
public static void main(String[] args){  
System.out.println(Adder.add(11,11));  
System.out.println(Adder.add(11,11,11));  
}}  
A.3-Static Method
class Student{  
     int rollno;  
     String name;  
     static String college = "ITS";  
     //static method to change the value of static variable  
     static void change(){  
     college = "BBDIT";  
     }  
     //constructor to initialize the variable  
     Student(int r, String n){  
     rollno = r;  
     name = n;  
     }  
     //method to display values  
     void display(){System.out.println(rollno+" "+name+" "+college);}  
}  
//Test class to create and display the values of object  
public class TestStaticMethod{  
    public static void main(String args[]){  
    Student.change();//calling change method  
    //creating objects  
    Student s1 = new Student(111,"Karan");  
    Student s2 = new Student(222,"Aryan");  
    Student s3 = new Student(333,"Sonoo");  
    //calling display method  
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}  

B.1Inheritance
class Animal{  
void eat(){System.out.println("eating...");}  
}  
class Dog extends Animal{  
void bark(){System.out.println("barking...");}  
}  
class BabyDog extends Dog{  
void weep(){System.out.println("weeping...");}  
}  
class TestInheritance2{  
public static void main(String args[]){  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}}  
B.2 Method Overriding
class Vehicle{  
  //defining a method  
  void run(){System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle{  
  //defining the same method as in the parent class  
  void run(){System.out.println("Bike is running safely");}  
  
  public static void main(String args[]){  
  Bike2 obj = new Bike2();//creating object  
  obj.run();//calling method  
  }  
} 

PRACTICAL 2:

1A Abstract class


  1. abstract class Shape{  

  2. abstract void draw();  

  3. }  

  4. //In real scenario, implementation is provided by others i.e. unknown by end user  

  5. class Rectangle extends Shape{  

  6. void draw(){System.out.println("drawing rectangle");}  

  7. }  

  8. class Circle1 extends Shape{  

  9. void draw(){System.out.println("drawing circle");}  

  10. }  

  11. //In real scenario, method is called by programmer or user  

  12. class TestAbstraction1{  

  13. public static void main(String args[]){  

  14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method  

  15. s.draw();  

  16. }  


  17. PRACTICAL 2: 1B interface


  1. interface Bank{  

  2. float rateOfInterest();  

  3. }  

  4. class SBI implements Bank{  

  5. public float rateOfInterest(){return 9.15f;}  

  6. }  

  7. class PNB implements Bank{  

  8. public float rateOfInterest(){return 9.7f;}  

  9. }  

  10. class TestInterface2{  

  11. public static void main(String[] args){  

  12. Bank b=new SBI();  

  13. System.out.println("ROI: "+b.rateOfInterest());  

  14. }}  



Practical 3

User defined exception

  1. class InvalidAgeException  extends Exception  

  2. {  

  3.     public InvalidAgeException (String str)  

  4.     {  

  5.         // calling the constructor of parent Exception  

  6.         super(str);  

  7.     }  

  8. }  

  9.     

  10. // class that uses custom exception InvalidAgeException  

  11. public class TestCustomException1  

  12. {  

  13.   

  14.     // method to check the age  

  15.     static void validate (int age) throws InvalidAgeException{    

  16.        if(age < 18){  

  17.   

  18.         // throw an object of user defined exception  

  19.         throw new InvalidAgeException("age is not valid to vote");    

  20.     }  

  21.        else {   

  22.         System.out.println("welcome to vote");   

  23.         }   

  24.      }    

  25.   

  26.     // main method  

  27.     public static void main(String args[])  

  28.     {  

  29.         try  

  30.         {  

  31.             // calling the method   

  32.             validate(13);  

  33.         }  

  34.         catch (InvalidAgeException ex)  

  35.         {  

  36.             System.out.println("Caught the exception");  

  37.     

  38.             // printing the message from InvalidAgeException object  

  39.             System.out.println("Exception occured: " + ex);  

  40.         }  

  41.   

  42.          }  

  43. }  


PRACTICAL 2: 1A Abstract class

  1. abstract class Shape{  

  2. abstract void draw();  

  3. }  

  4. //In real scenario, implementation is provided by others i.e. unknown by end user  

  5. class Rectangle extends Shape{  

  6. void draw(){System.out.println("drawing rectangle");}  

  7. }  

  8. class Circle1 extends Shape{  

  9. void draw(){System.out.println("drawing circle");}  

  10. }  

  11. //In real scenario, method is called by programmer or user  

  12. class TestAbstraction1{  

  13. public static void main(String args[]){  

  14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method  

  15. s.draw();  

  16. }  

  17. }  

  18. PRACTICAL 2: 1B interface

  1. interface Bank{  

  2. float rateOfInterest();  

  3. }  

  4. class SBI implements Bank{  

  5. public float rateOfInterest(){return 9.15f;}  

  6. }  

  7. class PNB implements Bank{  

  8. public float rateOfInterest(){return 9.7f;}  

  9. }  

  10. class TestInterface2{  

  11. public static void main(String[] args){  

  12. Bank b=new SBI();  

  13. System.out.println("ROI: "+b.rateOfInterest());  

  14. }}  



Practical 3

User defined exception

  1. class InvalidAgeException  extends Exception  

  2. {  

  3.     public InvalidAgeException (String str)  

  4.     {  

  5.         // calling the constructor of parent Exception  

  6.         super(str);  

  7.     }  

  8. }  

  9.     

  10. // class that uses custom exception InvalidAgeException  

  11. public class TestCustomException1  

  12. {  

  13.   

  14.     // method to check the age  

  15.     static void validate (int age) throws InvalidAgeException{    

  16.        if(age < 18){  

  17.   

  18.         // throw an object of user defined exception  

  19.         throw new InvalidAgeException("age is not valid to vote");    

  20.     }  

  21.        else {   

  22.         System.out.println("welcome to vote");   

  23.         }   

  24.      }    

  25.   

  26.     // main method  

  27.     public static void main(String args[])  

  28.     {  

  29.         try  

  30.         {  

  31.             // calling the method   

  32.             validate(13);  

  33.         }  

  34.         catch (InvalidAgeException ex)  

  35.         {  

  36.             System.out.println("Caught the exception");  

  37.     

  38.             // printing the message from InvalidAgeException object  

  39.             System.out.println("Exception occured: " + ex);  

  40.         }  

  41.   

  42.          }  

  43. }  






PRACTICAL 2: 1A Abstract class

  1. abstract class Shape{  

  2. abstract void draw();  

  3. }  

  4. //In real scenario, implementation is provided by others i.e. unknown by end user  

  5. class Rectangle extends Shape{  

  6. void draw(){System.out.println("drawing rectangle");}  

  7. }  

  8. class Circle1 extends Shape{  

  9. void draw(){System.out.println("drawing circle");}  

  10. }  

  11. //In real scenario, method is called by programmer or user  

  12. class TestAbstraction1{  

  13. public static void main(String args[]){  

  14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method  

  15. s.draw();  

  16. }  

  17. }  

  18. PRACTICAL 2: 1B interface

  1. interface Bank{  

  2. float rateOfInterest();  

  3. }  

  4. class SBI implements Bank{  

  5. public float rateOfInterest(){return 9.15f;}  

  6. }  

  7. class PNB implements Bank{  

  8. public float rateOfInterest(){return 9.7f;}  

  9. }  

  10. class TestInterface2{  

  11. public static void main(String[] args){  

  12. Bank b=new SBI();  

  13. System.out.println("ROI: "+b.rateOfInterest());  

  14. }}  



Practical 3

User defined exception

  1. class InvalidAgeException  extends Exception  

  2. {  

  3.     public InvalidAgeException (String str)  

  4.     {  

  5.         // calling the constructor of parent Exception  

  6.         super(str);  

  7.     }  

  8. }  

  9.     

  10. // class that uses custom exception InvalidAgeException  

  11. public class TestCustomException1  

  12. {  

  13.   

  14.     // method to check the age  

  15.     static void validate (int age) throws InvalidAgeException{    

  16.        if(age < 18){  

  17.   

  18.         // throw an object of user defined exception  

  19.         throw new InvalidAgeException("age is not valid to vote");    

  20.     }  

  21.        else {   

  22.         System.out.println("welcome to vote");   

  23.         }   

  24.      }    

  25.   

  26.     // main method  

  27.     public static void main(String args[])  

  28.     {  

  29.         try  

  30.         {  

  31.             // calling the method   

  32.             validate(13);  

  33.         }  

  34.         catch (InvalidAgeException ex)  

  35.         {  

  36.             System.out.println("Caught the exception");  

  37.     

  38.             // printing the message from InvalidAgeException object  

  39.             System.out.println("Exception occured: " + ex);  

  40.         }  

  41.   

  42.          }  

  43. }  


PRACTICAL 4

List

import java.util.*;
public class Main {
public static void main(String args[]){
//Create List object
List&lt;String&gt; mySubjects = new ArrayList&lt;&gt;();
 
//Add elements to list
mySubjects.add(&quot;Java&quot;);
mySubjects.add(&quot;Spring&quot;);
mySubjects.add(&quot;Hibernate&quot;);
 
 
//Add elements at specified position
mySubjects.add(1,&quot;SQL&quot;);
mySubjects.add(2,&quot;Oracle&quot;);
 
System.out.println(&quot;My Subjects:&quot;);
//Print all subjects
for(String subject : mySubjects){
System.out.println(subject);
}
 
//Print element on 2nd index
System.out.println(&quot;Element at 2nd index: &quot;+mySubjects.get(2));
}
}

Set

import java.util.*;
public class Main {
 
public static void main(String args[]){
//Create Set object
Set&lt;String&gt; mySubjects = new HashSet&lt;&gt;();
 
//Add elements to Set
mySubjects.add(&quot;Java&quot;);
mySubjects.add(&quot;Spring&quot;);
mySubjects.add(&quot;Hibernate&quot;);
 
System.out.println(&quot;My Subjects:&quot;);
//Print all subjects
for(String subject : mySubjects){
System.out.println(subject);
}
 
}
}

Map
A map in java, not extends the Collection interface. It represents a
group of special elements or objects. Every map element or object
contains key and value pair. A map can’t contain duplicate keys and
one key can refer to at most one value.
Example
import java.util.*;
public class Main {
 
public static void main(String args[]){
Map&lt;Integer,String&gt; mysubjects = new HashMap&lt;Integer,String&gt;();
 
mysubjects.put(1,&quot;Java&quot;);
mysubjects.put(2,&quot;Spring&quot;);
mysubjects.put(3,&quot;Oracle&quot;);
 

for(Map.Entry subject : mysubjects.entrySet())
System.out.println(subject.getKey()+&quot; - &quot;+subject.getValue());
 
}
 
Practical 5
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
 
class Biodata extends JFrame implements ActionListener
{
    private JLabel l1,l2,l3,l4;
    private JTextField n;
    private JRadioButton r1,r2;
    private ButtonGroup g;
    private JCheckBox c1,c2,c3;
    private JTextArea a;
    private JButton b;
     
     
    Biodata()
    {
        super("Enter Biodata");
        Container c = getContentPane();
        c.setLayout(new GridLayout(4,2));
         
        l1 = new JLabel("Name");
        c.add(l1);
         
        n = new JTextField("Enter your name",20);
        n.setToolTipText("Please enter your name");
        c.add(n);

        l4 = new JLabel("Gender");
        c.add(l4);
         
        r1 = new JRadioButton("Male",true);
        c.add(r1);
        r2 = new JRadioButton("Female",false);
        c.add(r2);
         
        g = new ButtonGroup();
        g.add(r1);
        g.add(r2);
         
        l2 = new JLabel("Qualification");
        c.add(l2);
         
        c1 = new JCheckBox("BTech");
        c.add(c1);
        c2 = new JCheckBox("MTech");
        c.add(c2);
        c3 = new JCheckBox("MCA");
        c.add(c3);
         
        l3 = new JLabel("Address");
        c.add(l3);
         
        a = new JTextArea(10,15);
        c.add(a);
         
        b = new JButton("Show");
        c.add(b);
        b.addActionListener(this);
        setVisible(true);
        setSize(400,400);
    }
     
     
   
        public void actionPerformed(ActionEvent e)
        {
            String s = ""+n.getText()+"\n";
            s += (r1.isSelected())?r1.getText()+"\n":r2.getText() +"\n";
            if(c1.isSelected()) s += (c1.getText()) + "  ";
            if(c2.isSelected()) s += (c2.getText()) + "  ";
            if(c3.isSelected()) s += (c3.getText());
            s += "\n"+a.getText()+"\n";
             
            JOptionPane.showMessageDialog(null,s);
        }
    
     
     
    public static void main(String args[])
    {   
        new Biodata();
    }
}

Practical 7 

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

public class Calculator extends JFrame implements ActionListener

{    

   JButton b10,b11,b12,b13,b14,b15; 

   JButton b[]=new JButton[10];

    int i,r,n1,n2;

    JTextField res;

    char op; 

   public Calculator()

  {

     super("Calulator");

      setLayout(new BorderLayout());

      JPanel p=new JPanel();

      p.setLayout(new GridLayout(4,4));

      for(int i=0;i<=9;i++)

      {

        b[i]=new JButton(i+"");

        p.add(b[i]);

        b[i].addActionListener(this);

      }

      b10=new JButton("+");

      p.add(b10);

      b10.addActionListener(this);

 

      b11=new JButton("-");

      p.add(b11);

      b11.addActionListener(this);

 

      b12=new JButton("*");

      p.add(b12);

      b12.addActionListener(this);

 

      b13=new JButton("/");

      p.add(b13);

      b13.addActionListener(this);

 

      b14=new JButton("=");

      p.add(b14);

      b14.addActionListener(this);

 

      b15=new JButton("C");

      p.add(b15);

      b15.addActionListener(this);

 

      res=new JTextField(10);

      add(p,BorderLayout.CENTER);

      add(res,BorderLayout.NORTH);

      setVisible(true);

      setSize(200,200);

     }

public void actionPerformed(ActionEvent ae)

{

  JButton pb=(JButton)ae.getSource();

if(pb==b15)

{

r=n1=n2=0;

res.setText("");

}

else

if(pb==b14)

{

  n2=Integer.parseInt(res.getText());

   eval();

   res.setText(""+r);

}

 

else

{

    boolean opf=false;

    if(pb==b10)

{ op='+';

  opf=true;

}

    if(pb==b11)

{ op='-';opf=true;}

  if(pb==b12)

{ op='*';opf=true;}

  if(pb==b13)

{ op='/';opf=true;}

  if(opf==false)

  {

      for(i=0;i<10;i++)

   {

   if(pb==b[i])

        {

              String t=res.getText();

           t+=i;

             res.setText(t);

   }

   }

  }

  else

  {

     n1=Integer.parseInt(res.getText());

     res.setText("");

  }

}

}

int eval()

{

switch(op)

{

  case '+':   r=n1+n2;  break;

  case '-':    r=n1-n2;   break;

  case '*':    r=n1*n2; break;

  case '/':    r=n1/n2; break;

 

}

return 0;

}

 

  public static void main(String arg[])

  {

      new Calculator();

   }

}

Practical No.8


AIM:

a. Write a Servlet that accepts a User Name from a HTML form and stores it as a cookie. Write another Servlet that returns the value of this cookie and displays it.

b. Write a Servlet that displays the names and values of the cookie stored on the client.

c. Write a Servlet that accepts a User Name from a HTML form and stores it as a session variable. Write another Servlet that returns the value of this session variable and displays it. 

Input:

index.html

<form action="servlet1" method="post">  

Name:<input type="text" name="userName"/><br/>  

<input type="submit" value="go"/>  

</form>  

Web.xml 

<?xml version="1.0" encoding="UTF-8"?> 

<web-app version="2.5" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 

<servlet> 

<description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</displaimport java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

public class SecondServlet extends HttpServlet { 

public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ 

response.setContentType("text/html"); 

PrintWriter out = response.getWriter(); 

Cookie ck[]=request.getCookies(); 

out.print("Hello "+ck[0].getValue()); 

out.close(); 

}catch(Exception e){System.out.println(e);} 

} y-name> <servlet-name>Servlet1</servlet-name> 

<servlet-class>FirstServlet</servlet-class> 

</servlet> 

<servlet> 

<description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>SecondServlet</servlet-name> 

<servlet-class>SecondServlet</servlet-class> 

</servlet> 

<servlet-mapping> 

<servlet-name>Servlet1</servlet-name> 

<url-pattern>/servlet1</url-pattern> 

</servlet-mapping> 

<servlet-mapping> 


FirstServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

  

  

public class FirstServlet extends HttpServlet {  

  

  public void doPost(HttpServletRequest request, HttpServletResponse response){  

    try{  

  

    response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  

          

    String n=request.getParameter("userName");  

    out.print("Welcome "+n);  

  

    Cookie ck=new Cookie("uname",n);//creating cookie object  

    response.addCookie(ck);//adding cookie in the response  

  

    //creating submit button  

    out.print("<form action='servlet2'>");  

    out.print("<input type='submit' value='go'>");  

    out.print("</form>");  

          

    out.close();  

  

        }catch(Exception e){System.out.println(e);}  

  }  

}  

SecondServlet.java

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

  

public class SecondServlet extends HttpServlet {  

  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

    try{  

  

    response.setContentType("text/html");  

    PrintWriter out = response.getWriter();  

      

    Cookie ck[]=request.getCookies();  

    out.print("Hello "+ck[0].getValue());  

  

    out.close();  

  

         }catch(Exception e){System.out.println(e);}  

    }  

      

  

}  

Practical No: 9

Aim:a. Write a registration Servlet that accepts the data for a given table and stores it in the database. 

b. Write a Servlet that displays all the records of a table. 




































a. Write a registration Servlet that accepts the data for a given table and stores it in the database. 

b. Write a Servlet that displays all the records of a table.

 Input:

   register.html

<!doctype html>  

   <body>  

      <form action="servlet/Register" method="post">  

         <fieldset style="width:20%; background-color:#ccffeb">

            <h2 align="center">Registration form</h2><hr>

            <table>

               <tr>

                  <td>Name</td>

                  <td><input type="text" name="userName" required /></td>

               </tr>  

               <tr>

                  <td>Password</td>

                  <td><input type="password" name="userPass" required /></td>

               </tr>  

               <tr>

                  <td>Email Id</td>

                  <td><input type="text" name="userEmail" required /></td>

               </tr>  

               <tr>

                  <td>Mobile</td>

                  <td><input type="text" name="userMobile" required/></td>

               </tr>  

               <tr>

                  <td>Date of Birth</td>

                  <td><input type="date" name="userDOB" required/></td>

               </tr>  

               <tr>

                  <td>Gender</td>

                  <td><input type="radio" name="gender" value="male" checked> Male

                  <input type="radio" name="gender" value="female"> Female </td></tr>

               <tr>

                  <td>Country</td>

                  <td><select name="userCountry" style="width:130px">  

                     <option>Select a country</option>  

                     <option>India</option>  

                     <option>America</option>  

                     <option>England</option>  

                     <option>other</option></select>

                  </td>

               </tr>

               <tr>

                  <td><input type="reset" value="Reset"/></td>

                  <td><input type="submit" value="Register"/></td>

               </tr>

            </table>

         </fieldset>  

      </form>  

   </body>  

</html>


Register.java

import jakarta.servlet.ServletException;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import java.io.*;  

import java.sql.*;  

public class Register extends HttpServlet

{  

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

     {  

          response.setContentType("text/html");  

          PrintWriter out = response.getWriter();  

          String name = request.getParameter("userName");  

          String pwd = request.getParameter("userPass");  

          String email = request.getParameter("userEmail");

          int mobile = Integer.parseInt(request.getParameter("userMobile"));

          String dob = request.getParameter("userDOB");  

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

          String country =request.getParameter("userCountry");  

          

          try

          {  

               //load the driver

               Class.forName("oracle.jdbc.driver.OracleDriver");  

               //create connection object

               Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql","root","Shriyash@11");  

               // create the prepared statement object

               PreparedStatement ps=con.prepareStatement("insert into registration values(?,?,?,?,?,?,?)");  

               ps.setString(1,name);  

               ps.setString(2,pwd);  

               ps.setString(3,email);  

               ps.setInt(4, mobile);

               ps.setString(5,dob);  

               ps.setString(6,gender);  

               ps.setString(7,country);  

               int i = ps.executeUpdate();  

               if(i>0)  

               out.print("You are successfully registered...");  

          }

          catch (Exception ex)

          {

               ex.printStackTrace();

          }  

          out.close();  

     }  

}


web.xml

<web-app>    

     <servlet>  

          <servlet-name>Register</servlet-name>  

          <servlet-class>Register</servlet-class>  

     </servlet>  

  

     <servlet-mapping>  

          <servlet-name>Register</servlet-name>  

          <url-pattern>/servlet/Register</url-pattern>  

     </servlet-mapping>  

  

     <welcome-file-list>  

          <welcome-file>register.html</welcome-file>  

     </welcome-file-list>    

</web-app>



Practical No: 10


Aim:

Write a Servlet that accepts a User Name from a HTML form and stores it as a session variable. Write another Servlet that returns the value of this session variable and displays it.


Input:

Index.html

<!DOCTYPE html>

<html>

    <head>

        <title>Bhavesh </title>

    </head>

    <body>

        <form action="welcome.jsp">  

            <input type="text" name="uname">  

            <input type="submit" value="go"><br/>  

        </form>  

    </body>

</html>


Welcome.jsp

<html>  

<body>  

    <% 

        String name=request.getParameter("uname");  

        out.print("Welcome "+name);  

    session.setAttribute("user",name);   

    %>  

    <a href="second.jsp">second jsp page</a>  

</body>  

</html>  


Second.jsp

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>Aye Yoooooo</title>

    </head>

    <body>

        <%   

            String name=(String)session.getAttribute("user");  

            out.print("Hello "+name);  

        %>  


    </body>

</html>


    

Comments

Popular posts from this blog

ADC