100% found this document useful (2 votes)
1K views77 pages

Laboratory Workbook: Sinhgad Institute of Management & Computer Application (SIMCA)

This document contains 15 programming questions and their solutions in Java. The questions cover basic Java concepts like loops, methods, constructors, classes, objects, exceptions, interfaces, inheritance and polymorphism. Sample inputs and outputs are provided for each program. The programs are part of a lab workbook for an MCA course at Sinhgad Institute of Management & Computer Application.

Uploaded by

priyanka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (2 votes)
1K views77 pages

Laboratory Workbook: Sinhgad Institute of Management & Computer Application (SIMCA)

This document contains 15 programming questions and their solutions in Java. The questions cover basic Java concepts like loops, methods, constructors, classes, objects, exceptions, interfaces, inheritance and polymorphism. Sample inputs and outputs are provided for each program. The programs are part of a lab workbook for an MCA course at Sinhgad Institute of Management & Computer Application.

Uploaded by

priyanka
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 77

STE Society’s

Sinhgad Institute of Management &


Computer Application (SIMCA)

Laboratory Workbook

Subject: Java Programming Lab

Course: MCA I - [Sem: I]

Prepared by,
Name : Priyanka Nitin Sonawane
Roll No. 20137
Div : A

1. Write a program to display “Welcome to SIMCA” 5 times on console.

Program:-

public class WelcomeSIMCA {

public static void main(String[] args) {


// TODO Auto-generated method stub

for(int i=0;i<5;i++) {

System.out.println("Welcome to SIMCA");

Output:-

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

2. Write a program to display “Welcome to SIMCA” 5 times using Constructor.

Program:-

public class Constructor2 {

Constructor2(){

for(int i=0;i<5;i++) {

System.out.println("Welcome to SIMCA");

public static void main(String[] args) {

// TODO Auto-generated method stub

Constructor2 c1 = new Constructor2();

System.out.println(c1);

Output:-

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

Welcome to SIMCA

Constructor2@71dac704
3. Write a program to Fibonacci series up to user define number.

Program:-

public class Fibonacci3 {

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = 10, t1 = 0, t2 = 1;

System.out.println("First"+n+"terms:");

for(int i=1;i<=n;i++) {

System.out.println(t1+"+");

int sum = t1+t2;

t1 = t2;

t2 = sum;

Output:-

3+

5+

8+

13+

21+

34+

4. Write a program to computer reverse number. Accept number from user and display on console.

Program:-

import java.util.Scanner;

public class Reverse4 {

public static void main(String[] args) {

// TODO Auto-generated method stub

int num = 0;

int reversesum = 0;

System.out.println("Input your number and press enter=");

Scanner sc = new Scanner(System.in);


num = sc.nextInt();

while(num!=0) {

reversesum = reversesum * 10;

reversesum = reversesum + num%10;

num = num/10;

System.out.println("Reverse of input number is="+reversesum);

sc.close();

Output:-

Input your number and press enter=

1234

Reverse of input number is=4321

5. Write a program to count the number of objects of a class.

Program:-

public class ObjectNumber5 {

static int count=0;

ObjectNumber5(){

count++;

public static void main(String[] args) {

// TODO Auto-generated method stub

ObjectNumber5 obj1 = new ObjectNumber5();

ObjectNumber5 obj2 = new ObjectNumber5();

ObjectNumber5 obj3 = new ObjectNumber5();

ObjectNumber5 obj4 = new ObjectNumber5();

System.out.println("Number of objects created="+count);

Output:-

Number of objects created=4


6. Write a program to assign object reference variable to another.

Program:-

class Data{

int data1;

int data2;

public class ObjectReference6 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Data d1 = new Data();

d1.data1 = 20;

Data d2 = d1;

d2.data2 = 40;

Data d3 = d2;

System.out.println("d3.Data1:"+d3.data1);

System.out.println("d3.Data2:"+d3.data2);

Output:-

d3.Data1:20

d3.Data2:40

7. Write a program to delete the reference to object and garbage collection .

Program:-

public class Garbage7 {

public void finalize() {

System.out.println("Object is garbage collected");

public static void main(String[] args) {

// TODO Auto-generated method stub

Garbage7 g1 = new Garbage7();

Garbage7 g2 = new Garbage7();

g1 = null;

g2 = null;
System.gc();

Output:-

Object is garbage collected

Object is garbage collected

8. Read only one parameter from command line argument and display the welcome message also check
the length.

Program:-

public class CommandLine8 {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i=0;i<args.length;i++) {

String s = args[i];

System.out.println(s);

Output:-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at CommandOperations.main(CommandOperations.java:7)

9. Read two numbers from command line and perform addition, subtraction, multiplication and division.

Program:-

public class CommandOperations {

public static void main(String[] args) {

// TODO Auto-generated method stub

int x,y;

int add,sub,mul;

int div;

x = Integer.parseInt(args[0]);

y = Integer.parseInt(args[1]);
add = x + y;

System.out.println("Addition of numbers="+add);

sub= x - y;

System.out.println("Subtraction of numbers="+sub);

mul= x * y;

System.out.println("Multiplication of numbers="+mul);

div= x / y;

System.out.println("Division of numbers="+div);

Output:-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at CommandOperations.main(CommandOperations.java:9)

10. Read a number from command line and check whether it is prime or not.

Program:-

public class Prime10 {

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = Integer.parseInt(args[0]);

int cnt = 0;

for(int i=2;i<=n/2;i++) {

if(n%i==0) {

cnt = 1;

if(cnt==0) {

System.out.println("Number is prime"+n);

}
else {

System.out.println("Number is not prime"+n);

Output:-

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at Prime10.main(Prime10.java:6)

11. Write a program to implement the polymorphism by calculating the area of rectangle and circle.

Program:-

class Overload{

void area(float x,float y) {

System.out.println("The area of Rectangle is="+x*y+"units");

void area(double x) {

double z = 3.14 * x * x;

System.out.println("The area of Circle is="+z);

class AreaRectangleCircle11

public static void main(String args[])

Overload a1 = new Overload();

a1.area(2.5);

a1.area(11,12);

Output:-

The area of Circle is=19.625

The area of Rectangle is=132.0units


12. Write a program in java to read a number from command line and check whether it is odd or even. If it
is even then display “You have entered correct no.” and if is odd generate user defined oddException.

Program:-

@SuppressWarnings("serial")

class OddEven extends Exception{

// TODO Auto-generated method stub

public OddEven(String s) {

super(s);

class OddEven12{

public static void main(String args[])

int x;

x = Integer.parseInt(args[0]);

if(x%2==0) {

System.out.println(x+"You entered correct number");

else

try {

throw new OddEven("OddException");

catch(OddEven e) {

System.out.println("Caught");

System.out.println(e.getMessage());

Output:-
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

at OddEven12.main(OddEven12.java:17)

13. Write a program to generate


1. ArithmeticException.
2. NumberFormatException.
3. ArrayIndexOutOfBounds Exception.

Program:-

public class Exceptions13 {

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

int num1 = 30, num2 = 0;

int output = num1 / num2;

System.out.println("Result:"+output);

catch(ArithmeticException e){

System.out.println("You shouldn't divide a number by zero.");

try {

int a[] = new int[10];

a[11] = 9;

catch(ArrayIndexOutOfBoundsException e1){

System.out.println("ArrayIndexOutOfBounds");

try

int num = Integer.parseInt("xyz");

System.out.println(num);

catch(NumberFormatException e) {
System.out.println("Number format exception occured");

Output:-

You shouldn't divide a number by zero.

ArrayIndexOutOfBounds

Number format exception occurred

14. Write a program to implement a user define exception “NotPrimeException”. Read number from
command line argument and check whether the number is prime or not. If it is prime then display the
message “Number is prime” and if it is not prime throw the exception “NotPrimeException”.

Program:-

class NotPrimeException extends Exception{

public NotPrimeException(String s) {

super(s);

public class PrimeException {

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = Integer.parseInt(args[0]);

int cnt = 0;

for(int i=2;i<=n/2;i++) {

if(n%i==0) {

cnt = 1;

if(cnt==0) {

System.out.println("Number is Prime"+n);

else

try {
throw new NotPrimeException("NotPrimeException");

catch(NotPrimeException e) {

System.out.println("Caught");

System.out.println(e.getMessage());

15. Write a java program using interface, which performs simple arithmetic operations such as addition,
subtraction, multiplication, division.

Program:-

import java.util.Scanner;

interface ArithmeticOperations{

public void add(int a,int b);

public void sub(int a,int b);

public void mul(int a,int b);

public void div(int a,int b);

public class InterfaceArithmetic implements ArithmeticOperations {

@Override

public void add(int a, int b) {

// TODO Auto-generated method stub

int c;

c = a + b;

System.out.println(c);

@Override

public void sub(int a, int b) {


// TODO Auto-generated method stub

int c;

c = a - b;

System.out.println(c);

@Override

public void mul(int a, int b) {

// TODO Auto-generated method stub

int c;

c = a * b;

System.out.println(c);

@Override

public void div(int a, int b) {

// TODO Auto-generated method stub

int c;

c = a / b;

System.out.println(c);

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("Enter two numbers");

int x = sc.nextInt();

int y = sc.nextInt();

ArithmeticOperations a1 = new InterfaceArithmetic();

System.out.println("Additon is:");

a1.add(x, y);

System.out.println("Substraction is:");

a1.sub(x, y);
System.out.println("Multiplication is:");

a1.mul(x, y);

System.out.println("Division is:");

a1.div(x, y);

sc.close();

Output:-

Enter two numbers

Additon is:

Substraction is:

-1

Multiplication is:

Division is:

16. Write a java code to create a thread object and start it.

Program:-

public class ThreadObject16 extends Thread{

public void run() {

System.out.println("Thread is running....");

public static void main(String[] args) {

// TODO Auto-generated method stub

ThreadObject16 t1 = new ThreadObject16();

t1.start();

}
}

Output:-

Thread is running....

17. Write a program that creates and run the following threads-

1. To print letter ‘A’ 75 times.

2. To print letter ‘B’ 100 times.

3. To print integer 1 to 100.

Program:-

class PrintChar implements Runnable{

private char charToPrint;

private int times;

public PrintChar() {

public PrintChar(char charToPrint,int times) {

this.charToPrint = charToPrint;

this.times = times;

@Override

public void run() {

for(int i=0;i<=times;i++) {

System.out.println(charToPrint);

class PrintNum implements Runnable{

private int lastNum;

public PrintNum(int lastNum) {

this.lastNum = lastNum;
}

@Override

public void run() {

for(int i = 0;i<lastNum;i++) {

System.out.println(" "+i);

public class Thread17 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Runnable printA = PrintChar('A',75);

Runnable printB = PrintChar('B',100);

Runnable print100 = PrintNum(100);

Thread t3 = new Thread(print100);

Thread t2 = new Thread(printB);

Thread t1 = new Thread(printA);

t1.start();

t2.start();

t3.start();

private static Runnable PrintNum(int i) {

// TODO Auto-generated method stub

return null;

private static Runnable PrintChar(char c, int i) {

// TODO Auto-generated method stub

return null;

}
}

18. Write a program to create a multiple threads.

Program:-

class MultithreadDemo extends Thread{

public void run() {

try

System.out.println("Thread"+Thread.currentThread().getId()+"is running..");

catch(Exception e)

System.out.println("Exception is caught");

public class MultipleThread {

public static void main(String[] args) {

// TODO Auto-generated method stub

int n = 8;

for(int i = 0;i < n;i++) {

MultithreadDemo m1 = new MultithreadDemo();

m1.start();

Output:-

Thread19is running..

Thread20is running..

Thread16is running..

Thread15is running..

Thread14is running..
Thread18is running..

19. Write a program to change name and priority of thread.

Program:-

public class Thread19 extends Thread {

public void run() {

public static void main(String[] args) {

// TODO Auto-generated method stub

Thread19 t1 = new Thread19();

t1.start();

System.out.println("T1 thread name:"+t1.getName());

System.out.println("After change name");

t1.setName("MyThread");

System.out.println("Get Name"+t1.getName());

System.out.println("T1 thread priority:"+t1.getPriority());

System.out.println("set t1 piority");

t1.setPriority(Thread.MAX_PRIORITY);

System.out.println("Get priority of t1:"+t1.getPriority());

Output:-

T1 thread name:Thread-0

After change name

Get NameMyThread

T1 thread priority:5

set t1 piority

Get priority of t1:5


20. Write a program containing three functions proca, procb and procc each is having try block and finally
block. Exception is thrown from proca which is caught.

Program:-

public class ExceptionFunction {

public void proca()

try {

int divideZero = 5/0;

catch(ArithmeticException e)

System.out.println("Arithmetic Exception:" +e.getMessage());

finally {

System.out.println("This is proca");

public void procb()

try {

int divideZero = 8/2;

catch(ArithmeticException e)

System.out.println("Arithmetic Exception:" +e.getMessage());

finally {

System.out.println("This is procb");

public void procc()

try {

int divideZero = 10/2;


}

catch(ArithmeticException e)

System.out.println("Arithmetic Exception:" +e.getMessage());

finally {

System.out.println("This is procc");

public static void main(String args[])

ExceptionFunction e1 = new ExceptionFunction();

e1.proca();

e1.procb();

e1.procc();

Output:-

Arithmetic Exception:/ by zero

This is proca

This is procb

This is procc

21. Write a program having interface A containing two methods meth1() and meth2(). interface
B extends A which contain method meth3() and one class which implements B.

Program:-
interface MyInterface

public void method1();

public void method2();

class Interface implements MyInterface

public void method1()


{

System.out.println("implementation of method1");

public void method2()

System.out.println("implementation of method2");

public static void main(String arg[])

MyInterface obj = new Interface();

obj.method1();

Output:-

implementation of method1

22 Design a program to create an *ArrayList*. Create a *Student* class, assign rollno,


name, and marks to him using constructor. Store 5 objects of Student class in
ArrayList. And display the records of the students who has more than 60 marks.

Source Code:

import java.util.ArrayList;

import java.util.Iterator;

public class Student {

int roll;

String name;

int marks;

public Student(int roll,String name, int marks)

this.roll=roll;

this.name=name;

this.marks=marks;
}

public static void main(String[] args) {

// TODO Auto-generated method stub

Student d1=new Student (1,"Anup",60);

Student d2=new Student (2,"Abhay",90);

Student d3=new Student (3,"Shubham",75);

Student d4=new Student (4,"Nisha",69);

Student d5=new Student (5,"Raj",98);

ArrayList <Student> s=new ArrayList<Student>();

s.add(d1);

s.add(d2);
s.add(d3);

s.add(d4);

s.add(d5);

for (Student i : s)

if(i.marks>60)

System.out.print(i.roll+"\t");

System.out.print(i.name+"\t");

System.out.print(i.marks+"\t");

System.out.println();

Output:
23 Design a program to create an *LinkedList*. Create a *Employee* class, assign emp_id,
emp_name and emp_salary to him using constructor. Store 5 objects of
Employee class in LinkedList. Update the salary of the all the Employees with 10%.

Source Code:

import java.util.*;
public class Employee {
int emp_id;
String emp_name;
double emp_sal;
public Employee(int id,String name,double sal)
{
this.emp_id=id;
this.emp_name=name;
this.emp_sal=sal;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Program to create 5 objects of Employee class Store it in
LinkedList and update salary of all Employees by 10 %."); Employee
Employee e1=new Employee(11,"Aman",25000);
Employee e2=new Employee(12,"Alex",20000);
Employee e3=new Employee(13,"Ruhi",17000);
Employee e4=new Employee(14,"Nikita",15000);
Employee e5=new Employee(15,"Keshav",27000);
<Employee> e=new LinkedList<Employee>();
e.add(e1);
e.add(e2);
e.add(e3);
e.add(e4);
e.add(e5);
System.out.println("Employee records are:");
for(Employee i: e)
{
System.out.println("Employee id:"+i.emp_id);
System.out.println("Employee Name:"+i.emp_name);
System.out.println("Employee Salary:"+i.emp_sal);
System.out.println();
}
System.out.println("Updated Records are:");
for(Employee i: e)
{
double sal=(i.emp_sal/100)*10;
i.emp_sal=i.emp_sal+sal;
System.out.println("Employee id:"+i.emp_id);
System.out.println("Employee Name:"+i.emp_name);
System.out.println("Employee Salary:"+i.emp_sal);
System.out.println();
}

Output:
24 Write the program to demonstrate the TreeSet class.

Source Code:

import java.util.*;
public class tree {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println("Program to demonstrate the TreeSet class.");
TreeSet<String> al=new TreeSet<String>();
al.add("Raj");
al.add("Rushikesh");
al.add("Raman");
al.add("Rajesh");
Iterator<String> itr=al.iterator();
while(itr.hasNext())
{ System.out.println(itr.next());
}
}
}

Output:
25 Write the program to demonstrate the HashMap class.

Source Code:

import java.util.*;
public class hash {

public static void main(String[] args) {


// TODO Auto-generated method stub
System.out.println("Program to demonstrate the HashMap class.");
HashMap<Integer,String> map=new
HashMap<Integer,String>();
map.put(1,"Swapnil");
map.put(2,"Yogesh");
map.put(3,"Nandan");
map.put(4,"Ajay");

System.out.println("Iterating Hashmap...");
for(Map.Entry m:map.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}

}
}

Output:
26 Write an Application
to fill university examination form. Use text box for name, mobile no, email id. Text area for
address. List box for city. Radio button for gender. Checkbox for subjects. Combo box for
course. Also display submit button. After clicking
submit button display report on console.

Source Code:

P24.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>University Exam Form</title>

</head>

<body>

<form action="dis.jsp" method="get">

<h1>University Exam Form</h1>

<h3>Enter Name: </h3> <br>

<input type="text" name="username"><br>

<h3>Enter Mobile Number: </h3> <br>

<input type="text" name="mobile"><br>

<h3>Enter Email-id: </h3> <br>

<input type="text" name="email"><br>

<h3>Enter Address: </h3> <br>

<textarea rows="2" cols="20" name="addr"></textarea>


<h3><label for="gender">Gender: </label></h3>

<input type="radio" id="gender" name="gender" value="male"/>Male

<input type="radio" id="gender" name="gender" value="female"/>Female <br/>


<h3>Subject:</h3><br>

<input type="checkbox" name="sub" value="NetWork Technologies"/>

<label for="NT">NetWork Technologies</label> <br>

<input type="checkbox" name="sub" value="Operating System"/>

<label for="OS">Operating System</label> <br>

<input type="checkbox" name="sub" value="DSA"/>

<label for="DSA">DSA</label> <br>

<input type="checkbox" name="sub" value="OOSE"/>

<label for="OOSE">OOSE</label> <br>

<input type="checkbox" name="sub" value="Java"/>

<label for="Java">Java</label> <br>

<h3>City: </h3>

<select Name="city" Size="3" name="city">

<option> Lonavala </option>

<option> Ambegaon </option>

<option> Vadgaon </option>

<option> Narhe </option>

</select> <br>

<h3>Course:</h3>

<label for="course">Choose a course:</label>

<select name="course" name="course">

<option value="MCA">MCA</option>

<option value="MBA">MBA</option>
<option value="BCA">BCA</option>

<option value="BBA">BBA</option>

</select><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

dis.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>University Exam Form</title>

</head>

<body>

<% String name=request.getParameter("username");

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

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

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

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

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

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

String s[] = request.getParameterValues("sub"); %>


<h3>Name is:</h3> <%=name %>

<h3>Mobile is:</h3> <%=mobile %>

<h3>Email is:</h3> <%=email %>

<h3>Address is:</h3> <%=addr %>

<h3>Gender is:</h3> <%=g %>

<h3>Subjects are:</h3> <%for(int i=0;i<s.length;i++){out.println(s[i]+",");}%>

<h3>city is:</h3> <%=city %>

<h3>course is:</h3> <%=course %>

</body>

</html>

Output:
27 Design a program to open a frame, and on WindowClosing event close the frame window
using adapter class.

Source Code:

import java.awt.*;
import java.awt.event.*;
public class AdapterExample extends WindowAdapter{
Frame f;
AdapterExample(){ f=new
Frame();
f.addWindowListener(this);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
f.dispose();
}
public static void main(String[] args) {
new AdapterExample();
}
}

Output:
28 Design a program to display a frame which shows x and y coordinates on

Mousemove event using anonymous class.

Source Code:

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class mouse {
public static void main(String args[]) {
Frame frame = new Frame("AnonymousEventExample");
Label l=new Label();
l.setBounds(20,40,100,20);
frame.add(l);
addMouseMotionListener(frame);
frame.setSize(400,400);
frame.setLayout(null);
frame.setVisible(true);
new MouseMotionListener()
{

public void mouseMoved(MouseEvent e) {


l.setText("X="+e.getX()+", Y="+e.getY());
}
public void mouseDragged(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());

}
};
}
}

Output:
29 Design a JDBC program to displays the details of employees (eno, ename,

department, sal) whose department is Management.

Source Code:

import java.sql.*;

public class Lab {

public static void main(String[] args) {

System.out.println("Program to display Employee details who are in Management


Department");

try

Class.forName("com.mysql.jdbc.Driver");

Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/lab",

"root","");

PreparedStatement ps=con.prepareStatement("select * from employee where dept=?");

ps.setString(1,"Management");

ResultSet rs=ps.executeQuery();

while(rs.next())

System.out.printf(rs.getInt(1)+"\n");

System.out.printf(rs.getString(2)+"\n");

System.out.printf(rs.getString(3)+"\n");

System.out.print(rs.getInt(4));

System.out.println();

}
catch(Exception e)

System.out.println(e);

Output:
30 Design JDBC application for Student Feedback Form [Assume suitable table
structure].

Source Code:

sf.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Student Feedback</title>

</head>

<body>

<form action="sf.jsp" method="get">

<h1>Student Feedback Form</h1>

<h3>Enter PRN Number: </h3> <br>

<input type="text" name="prn"><br>

<h3>Enter Name: </h3> <br>

<input type="text" name="username"><br>

<h3>Enter Mobile Number: </h3> <br>

<input type="text" name="mobile"><br>

<h3>Enter Email-id: </h3> <br>

<input type="text" name="email"><br>

<h3>Enter Address: </h3> <br>

<textarea rows="4" cols="50" name="addr"></textarea>

<h3>Enter Your Feedback:</h3><br>

<textarea rows="11" cols="100" name="feed"></textarea> </br>


<input type="submit" value="Submit">

</form>

</body>

</html>

sf.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<%@ page import="java.sql.*"%>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Student Feedback Form</title>

</head>

<body>

<% String prn=request.getParameter("prn");

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

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

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

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

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

try

{ Class.forName("com.mysql.jdbc.Driver");

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

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


ps.setString(1,prn);

ps.setString(2,name);

ps.setString(3,mobile);

ps.setString(4,email);

ps.setString(5,addr);

ps.setString(6,feed);

int i=ps.executeUpdate();

if(i>0)

out.println("<h1>Thank You Your FeedBack Is Submitted Successfully!!</h1>");

else

out.println("Error Please Try Again Later!!");

catch(Exception e)

out.println(e);

%>

</body>

</html>
Output:
31 Design a java program to accept the empno from user and update the salary of employee
and display the updated record on screen. Hint employee table has fields
empno, ename, address, desg, salary.

Source Code:

import java.sql.*;

import java.util.*;

public class emp {

public static void main(String[] args) {

System.out.println("Program to accept Empno from user and update his salary");

try

Scanner sc=new Scanner(System.in);

System.out.println("Enter employee id:");

int empno=sc.nextInt();

System.out.println("Enter new Salary");

int sal=sc.nextInt();

Class.forName("com.mysql.jdbc.Driver");

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

PreparedStatement ps=con.prepareStatement("update emp set sal=? where eno=?");

ps.setInt(1,sal);

ps.setInt(2,empno);

int i=ps.executeUpdate();

if(i>0)

System.out.println("Salary Updated Successfully");

}
else

System.out.println("Error");

ps=con.prepareStatement("select * from emp where eno=?");

ps.setInt(1,empno);

ResultSet rs=ps.executeQuery();

if(rs.next())

System.out.println(rs.getInt(1));

System.out.println(rs.getString(2));

System.out.println(rs.getString(3));

System.out.println(rs.getString(4));

System.out.println(rs.getInt(5));

catch(Exception e)

{ System.out.println(

e);

}
Output:
32 Design a servlet program illustrating its lifecycle.

Source Code:

index.jsp

<!DOCTYPE html >


<head>
<title>Servlet Lifecycle Example</title>
</head>
<body>
<form action="ServletLifecycle" method="post">
<input type="submit" value="Make request" />
</form>
</body>
</html>

ServletLifecycle.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletLifecycleExample extends GenericServlet {


@Override
public void init() {
// initialize the servlet, and print something in the console.
System.out.println("Servlet Initialized!");
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Servlet called from jsp page!");
}
public void destroy() {
}
}
Output:
33 Design a servlet application to insert records of the Book Publishers into database table
and display record in tabular format. Assume suitable structure. Design HTML,
web.xml, servlet class.

Source Code:

bp.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Book Publisher</title>

</head>

<body>

<form action="bp" method="get">

<h2><a href="display">See Book Publisher Records</a></h2>

<h1>Book Publisher Form</h1>

<h3>Enter Author Name: </h3> <br>

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

<h3>Enter Book Name: </h3> <br>

<input type="text" name="bname"><br>

<h3>Enter Book Publish Year: </h3> <br>

<input type="text" name="bpy"><br>

<h3>Enter Email-id: </h3> <br>

<input type="text" name="email"><br>

<input type="submit" value="Submit">

</form>

</body>
</html>

bp.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class bp extends HttpServlet {

private static final long serialVersionUID = 1L;

public bp() {

super();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.getWriter().append("Served at: ").append(request.getContextPath());

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException { PrintWriter

pw;

response.setContentType("text/html");

pw=response.getWriter();
String name=request.getParameter("name");

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

int bpy=request.getParameter("bpy");

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

try

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/lab

,”root”,””);

PreparedStatement pstmt=con.prepareStatement(“insert into bp values (?,?,?,?)”);

pstmt.setString(1, name);

pstmt.setString(2, bname);

pstmt.setInt(3,bpy);

pstmt.setString(4, email);

int x=pstmt.executeUpdate();

if(x==1)

pw.println("Values Inserted Successfully");

catch(Exception e)

e.printStackTrace();

}
pw.close();

display.java

import java.io.*; import

javax.servlet.*; import

javax.servlet.http.*; import

java.sql.*;

public class display extends HttpServlet

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,


ServletException

PrintWriter out = res.getWriter();

res.setContentType("text/html");

out.println("<html><body>");

try

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lab",


"root", "");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select * from bp");

out.println("<table border=1 width=50% height=50%>");


out.println("<tr><th>Author Name</th><th>Book Name</th><th>Publish
Year</th><th>Email</th></tr>");

while (rs.next())

String n = rs.getString("aname");

String bn = rs.getString("bname");

String bpy = rs.getInt("bpy");

String email= rs.getString(“email”);

out.println("<tr><td>" + n + "</td><td>" + bn + "</td><td>" + bpy + "</td><td>" +


email + "</td></tr>");

} out.println("</table>");

out.println("</html></body>");

con.close();

catch (Exception e)

out.println(e);

web.xml

<web-app>
<servlet>
<servlet-name>bp</servlet-name>
<servlet-class>bp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bp</servlet-name>
<url-pattern>bp</url-pattern>
</servlet-mapping>
</web-app>

Output:
34 Design html page to accept Zoom registration form. Design Servlet code to store
registration details in database. Assume suitable table structure.

Source Code:

zrf.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Book Publisher</title>

</head>

<body>

<form action="zrf" method="get">

<h1>Zoom Registration Form</h1>

<h3>Enter Name: </h3> <br>

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

<h3>Enter Email: </h3> <br>

<input type="text" name="email"><br>

<h3>Enter Age: </h3> <br>

<input type="text" name="age"><br>

<input type="submit" value="Submit">

</form>

</body>

</html>
zrf.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class zrf extends HttpServlet {

private static final long serialVersionUID = 1L;

public zrf() {

super();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.getWriter().append("Served at: ").append(request.getContextPath());

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException { PrintWriter

pw;

response.setContentType("text/html");

pw=response.getWriter();

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

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

int age=request.getParameter("age");
try

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/lab

,”root”,””);

PreparedStatement pstmt=con.prepareStatement(“insert into zrf values (?,?,?)”);

pstmt.setString(1, name);

pstmt.setString(2, email);

pstmt.setInt(3, age);

int x=pstmt.executeUpdate();

if(x==1)

pw.println("Values Inserted Successfully");

catch(Exception e)

e.printStackTrace();

} pw.close();

}
Output:
35 Design a ser vlet cod e, to cr eate an d ad d co oki e on cli en t’ s machi n e, th at
stores username, current date and display the same.

Source Code:

cookie.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Book Publisher</title>

</head>

<body>

<form action="c1" method="get">

<h1>Cookie Example</h1>

<h3>Enter UserName: </h3> <br>

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

<input type="submit" value="Submit">

</form>

</body>

</html>

c1.java

import java.io.*; import

javax.servlet.*; import

javax.servlet.http.*; import

java.util.Date;

public class c1 extends HttpServlet


{

public void doGet(HttpServletRequest request,

HttpServletResponse response) {

try{ response.setContentType("text/html");

PrintWriter pwriter = response.getWriter();

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

String date= date.toString();

pwriter.print("Hello "+name);

Cookie c1=new Cookie("UserName",name);

Cookie c2=new Cookie("Date",date);

response.addCookie(c1);

response.addCookie(c2);

pwriter.print("<br><a href='welcome'>View Details</a>");

pwriter.close();

}catch(Exception exp)

{ System.out.println(exp

);

c2.java

import java.io.*; import

javax.servlet.*; import

javax.servlet.http.*;

public class c2 extends HttpServlet {


public void doGet(HttpServletRequest request,

HttpServletResponse response){

try{ response.setContentType("text/html");

PrintWriter pwriter = response.getWriter();

Cookie c[]=request.getCookies();

//Displaying User name value from cookie

pwriter.print("Name: "+c[1].getValue());

pwriter.print("Date: "+c[2].getValue());

pwriter.close();

}catch(Exception exp)

{ System.out.println(exp

);

Output:
36 Cr eate a b ean cl ass of emp l oyee sets i t’ s all th e pr oper ty b y u si n g JSP
code. Create HTML page to accept employee information.

Source Code:

emp.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Employee Details</title>

</head>

<body>

<form action="emp.jsp" method="get">

<h1>Bean Class For Employee</h1>

<h3>Enter Name: </h3> <br>

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

<h3>Enter Department: </h3> <br>

<input type="text" name="dept"><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

emp.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ page import="lab.Employee" %>


<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>University Exam Form</title>

</head>

<% String name=request.getParameter("name");

String dept=request.getParameter("dept");%>

<jsp:useBean id="employee" class="lab.Employee" />

<jsp:setProperty name="employee" property="name" value="<%=name %>" />

<jsp:setProperty name="employee" property="dept" value="<%=dept %>" />

<div>

<h3>Employee Details</h3>

</div>

<jsp:getProperty name="employee" property="name" /><br>

<jsp:getProperty name="employee" property="dept" />

</body>

</html>

Employee.java

public class Employee {


private String name;
private String dept;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getDept() {


return dept;
}

public void setDept(String dept) {


this.dept = dept;
}

Output:
37 Design a program to create HTML form with two text box to enter numbers. When page
is submitted to JSP, it calculate division of given no. if denominator is
zero then generate an error page.

Source Code:

div.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Division</title>

</head>

<body>

<h1>Division Of Two Number</h1>

<form action="div.jsp" method="get">

<h3>No1:</h3><input type="text" name="n1" /><br/><br/>

<h3>No2:</h3><input type="text" name="n2" /><br/><br/>

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

</form>

</body>

</html>

div.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>
<meta charset="ISO-8859-1">

<title>Division</title>

</head>

<body>

<% String num1=request.getParameter("n1");

String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);

int b=Integer.parseInt(num2);

int c=a/b;

out.print("<h3>division of numbers is: </h3>"+"<h3>"+c+"</h3>");

%>

</body>

</html>

Output:
38 Create an HTML page to accept two numbers from user, and on *divide*
button click send the request to server. *Jsp* page will accept the request And display
division of the numbers as a response to the client.(*use exception handling in jsp*).

Source Code:

div.html

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Division</title>

</head>

<body>

<h1>Division Of Two Number</h1>

<form action="div.jsp" method="get">

<h3>No1:</h3><input type="text" name="n1" /><br/><br/>

<h3>No2:</h3><input type="text" name="n2" /><br/><br/>

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

</form>

</body>

</html>

div.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>
<meta charset="ISO-8859-1">

<title>Division</title>

</head>

<body>

<%@ page errorPage="err.jsp" %>

<% String num1=request.getParameter("n1");

String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);

int b=Integer.parseInt(num2);

int c=a/b;

out.print("<h3>division of numbers is: </h3>"+"<h3>"+c+"</h3>");

%>

</body>

</html>

err.jsp

<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

Output:
39 Design a JSP code to connect to a database using beans. Display the details of Book
table. Design JSP code to search a student placement details from the
placement database by student id.

Source Code:

bean.java

import java.io.*;

import java.sql.*;

public class bean

private int bpy;

private String author;

private String bname;

public int getbpy()

try{

Class.forName("com.mysql.jdbc.Driver);

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/lab","root","");
PreparedStatement stmt=con.prepareStatement("select * from
from bp where bname=?");

ps.setString(1,bname);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getInt("bpy");

break;
}

catch(Exception e)

System.out.println(e);

public String getauthor()

try{

Class.forName("com.mysql.jdbc.Driver);

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/lab","root","");
PreparedStatement stmt=con.prepareStatement("select * from
from bp where bname=?");

ps.setString(1,bname);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getString("author");

break;

catch(Exception e)

System.out.println(e);
}

public String getbname()

try{

Class.forName("com.mysql.jdbc.Driver);

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

PreparedStatement stmt=con.prepareStatement("select * from from bp where bname=?");

ps.setString(1,bname);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getString("bname");

break;

catch(Exception e)

System.out.println(e);

public void setbname(String bname)

this.author=bname;

}
}

bean.jsp

<html>

<head>

<title>get and set properties Example</title>

</head>

<body>

<jsp:useBean id = "book" class = "bean">

<jsp:setProperty name = "book" property = "setbname" value = "There you are"/>

</jsp:useBean>

<p>Book Name:

<jsp:getProperty name = "book" property = "getbname"/>

</p>

<p>Author Name:

<jsp:getProperty name = "book" property = "getauthor"/>

</p>

<p>Book Publish Year:

<jsp:getProperty name = "book" property = "getbpy"/>

</p>

</body>

</html>
student.java

import java.io.*;

import java.sql.*;

public class student

private int sid;

private String sname;

private String company;

public int getsid()

try{

Class.forName("com.mysql.jdbc.Driver);

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/lab","root","");
PreparedStatement stmt=con.prepareStatement("select * from
from stud where sid=?");

ps.setInt(1,sid);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getInt("sid");

break;

catch(Exception e)

{
System.out.println(e);

public String getsname()

try{

Class.forName("com.mysql.jdbc.Driver);

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/lab","root","");
PreparedStatement stmt=con.prepareStatement("select * from
from stud where sid=?");

ps.setInt(1,sid);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getString("sname");

break;

catch(Exception e)

System.out.println(e);

public String getcompany()

{
try{

Class.forName("com.mysql.jdbc.Driver);

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

PreparedStatement stmt=con.prepareStatement("select * from from stud where sid=?");

ps.setInt(1,sid);

ResultSet rs=stmt.executeQuery();

if(rs.next())

return rs.getString("company");

break;

catch(Exception e)

System.out.println(e);

public int setsid(int sid)

this.sid=sid;

student.jsp

<html>

<head>
<title>get and set properties Example</title>

</head>

<body>

<jsp:useBean id = "students" class = "student">

<jsp:setProperty name = "students" property = "sid" value = "102"/>

</jsp:useBean>

<p>Student Id:

<jsp:getProperty name = "students" property = "getsid"/>

</p>

<p>Student Name:

<jsp:getProperty name = "students" property = "getsname"/>

</p>

<p>Student Company:

<jsp:getProperty name = "students" property = "getcompany"/>

</p>

</body>

</html>
Output:

You might also like