0% found this document useful (0 votes)
6 views

Surajjava 1

Uploaded by

surinegi8958
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Surajjava 1

Uploaded by

surinegi8958
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.

: -63

Q1. Write a java program to calculate sum of last digits of two numbers.

Program:-

public class AddLastDigits


{
public static int addLastDigits(int input1, int input2)
{
return Math.abs(input1 % 10) + Math.abs(input2 % 10);
}
public static void main(String[] args)
{
System.out.println(addLastDigits(123,234));
}
}
Output:- 7

Q2. Write a java program to calculate sum of even digit

Program:-

public class EvenDigitsSum {


public static int evenDigitsSum(int input1) {
int sum = 0;

while (input1 != 0) {
int digit = input1 % 10;
if (digit % 2 == 0) sum += digit;
input1 /= 10;
}

return sum;
}
public static void main(String[] args)
{
System.out.println(evenDigitsSum(12345));
}
}

Output: - 6
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q3. Write a java program to calculate cyclic sum of given number.


Hint:- If given number:- 12345
(1+2+3+4+5)+(2+3+4+5)+(3+4+5)+(4+5)+(5)
=>55

Program:-
class TestCyclic
{
public static void main(String[] args)
{
System.out.println(cyclic(12345));

public static int cyclic(int input1)


{
int n=input1;
int rem=0;
int sum=0;
int c=0;
while(n>0)
{
rem=n%10;
n=n/10;
c++;
}
n=input1;
String s=String.valueOf(n);
System.out.println("s==>"+s);
String s2="";
for(int i=0;i<c;i++)
{
s2=s.substring(i);
System.out.println("after sub string"+s2);
n=Integer.parseInt(s2);
while(n>0)
{
rem=n%10;
n=n/10;
sum=sum+rem;
}

}
return sum;
}}
Output: - 55
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q4. Write a java program to generate PIN according following condition


Hint:-
Step 1. If sum of length of input string is single digit then PIN= SUM
Step 2 (if sum in step 1 is two digits)
Calculate again sum of digit
For example
Input String:-
String s="abcd abcdef"
first word length =4
second word length=6
4+6=10

if sum of length is single digit then pin =sum


else again sum = 1+0
pin=1
Program:-
class GenratePin
{
public static void main(String[] args)
{
String s="abcdef abcdef";
System.out.println(pin(s));
}

public static int pin(String input1)


{
String[] lst=input1.split(" ");
int sum=0;
for(String s: lst)
{
sum=sum+s.length();
}
int pin=0;
int n=sum; int rem=0; int s=0;
if(sum<0)
{
pin=sum;
}
else
{ while(true)
{
while(n>0)
{
rem=n%10;
s=s+rem;
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

n=n/10;
}
if(s<10)
break;

n=s;
}
pin=s;
}
return pin;
}
}
Output: - 1

Q5 Create PIN using three given input numbers


"Secure Assets Private Ltd", a small company that deal with digital lockers which can be
locked and unlocked using PINs(password). You have been asked to work on the module
that is expected to generate PINs using
three input numbers.
Assumption: The three given input numbers will always consist of three digit i.e. each of
them will be in the
range >=100 and <=999
100<=input1<=999
100<=input2<=999
100<=input3<=999
Below are the rules for generating the PIN-
-The PIN should be made up of 4 digits
-The unit(ones) position of the PIN should be the tens position of
the three input numbers.
-The hundreds position of the PIN should be the least of the hundred position of the three
input
numbers
the three input numbers
-The tens position of the PIN should be the least of the tens position of the three input
numbers
-The hundred position of the PIN should be the least of the hundreds position of the three
input numbers
-The thousand position of the PIN should be the maximum of all the digits in the three
input numbers.

Example 1-
input1=123
input2=582
input3=175

then PIN 8122


Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Example 2-
input1=190
input2=267
input3=853

then PIN 9150


Program: -
class TestPin
{
public static void main(String[] args)
{
System.out.println(pin(123,582,175));
}

public static int pin(int input1, int input2, int input3)


{
input1=Math.abs(input1);
input2=Math.abs(input2);
input3=Math.abs(input3);
System.out.println(input1);
System.out.println(input2);
System.out.println(input3);
int unit1=0;
int unit2=0;
int unit3=0;
int tens1=0;
int tens2=0;
int tens3=0;
int hund1=0;
int hund2=0;
int hund3=0;
int pin=0;
int rem=0;

while(input1>0)
{
rem=input1%10;
unit1=rem;
input1=input1/10;
break;

}
System.out.println("unit 1=> "+unit1);

while(input2>0)
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

{
rem=input2%10;
unit2=rem;
input2=input2/10;
break;

System.out.println("unit 2=> "+unit2);


while(input3>0)
{
rem=input3%10;
unit3=rem;
input3=input3/10;
break;

}
System.out.println("unit 3=> "+unit3);

while(input1>0)
{
rem=input1%10;
tens1=rem;
input1=input1/10;
break;

}
System.out.println("tens 1=> "+tens1);
while(input2>0)
{
rem=input2%10;
tens2=rem;
input2=input2/10;
break;

}
System.out.println("tens 2=> "+tens2);
while(input3>0)
{
rem=input3%10;
tens3=rem;
input3=input3/10;
break;

}
System.out.println("tens 3=> "+tens3);
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

while(input1>0)
{
rem=input1%10;
hund1=rem;
input1=input1/10;

}
System.out.println("hund 1=> "+hund1);
while(input2>0)
{
rem=input2%10;
hund2=rem;
input2=input2/10;

}
System.out.println("hund 2=> "+hund2);
while(input3>0)
{
rem=input3%10;
hund3=rem;
input3=input3/10;

}
System.out.println("hund 3=> "+hund3);

int unitmax=Math.max(unit1,unit2);
unitmax=Math.max(unit3,unitmax);
System.out.println(unitmax);

int tensmax=Math.max(tens1,tens2);
tensmax=Math.max(tens3,tensmax);
System.out.println(tensmax);

int hundmax=Math.max(hund1,hund2);
hundmax=Math.max(hund3,hundmax);
System.out.println(hundmax);

int big=Math.max(unitmax,tensmax);
big=Math.max(hundmax,big);
System.out.println(big);

int unitmin=Math.min(unit1,unit2);
unitmin=Math.min(unit3,unitmin);
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

int tensmin=Math.min(tens1,tens2);
tensmin=Math.min(tens3,tensmin);

int hundmin=Math.min(hund1,hund2);
hundmin=Math.min(hund3,hundmin);

pin=big;

pin=pin*10+hundmin;
pin=pin*10+tensmin;
pin=pin*10+unitmin;

return pin;

}
}
Output: - 8122

Q6. Write a java program to find nth position Fibonacci number.


Program:-
class NthFib
{
public static void main(String[] args)
{
System.out.println("Nth position fibonacci number is "+nthfib(6));

}
public static int nthfib(int input1)
{
int a=0;
int b=1;
int f=0;
if(input1==1)
{
return 0;
}
else if(input1==2)
{
return 1;

}
else
{
for(int i=3;i<=input1;i++)
{
f=a+b;
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

a=b;
b=f;

}
return f;
}
}
}
Output: - Nth position Fibonacci number is 6

Q7. Create a class Box that uses a parameterized constructor to initialize the dimensions of
a box. The dimensions of the Box are width, height, depth. The class should have a method
that can return the volume of the box. Create an object of the Box class and test the
functionalities.

Program:-
class Box
{
int width, depth , height;
Box(int width, int depth , int height)
{
this.width=width;
this.depth=depth;
this.height=height;
}
public int volumeBox()
{
return(width*depth*height);
}
public static void main(String[] args)
{
Box b=new Box(2,2,4);
System.out.println("Volume of a Box "+b.volumeBox());
}
}
Output:- Volume of a Box 16
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q8. Create a new class called Calculator with the following methods:
1. A static method called powering(int n1, int n2) :- This method should return n1
to the power n2.
2. A static method called powerDouble(double n1, int n2) :- This method should
return n1 to the power n2.
3. Invoke both the methods and test the functionalities.

Program: -
class Calculator
{
static int powerInt(int n1, int n2)
{

return( (int) Math.pow(n1,n2));

}
static double powerDouble(double n1, int n2)
{
return (Math.pow(n1,n2));
}
public static void main(String[] args)
{
System.out.println("2 to the power 3 "+powerInt(2,3));
System.out.println("2.2 to the power 3 "+powerDouble(2.2,3));
}
}
Output:- D:\programming\fileprogram>java Calculator
2 to the power 3 8
2.2 to the power 3 10.648000000000003

Q9. Create a class Author with the following information


Member variables:
Name (String), email (String) and gender (char)
Parameterized Constructor: To initialize the variables
Create a class Book with the following information
Member variables:
Name (String), author (of the class Author you have just created ), price (double)
and qtyInStock (int)
Parameterized Constructor: To initialize the variables
Getters and Setters method for all the member variables.

In the main method create a book object and print all details of the book.
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Program: -
package com.suraj.programs;

public class Author


{
String name;
String email;
char gender;
public Author(String name, String email, char gender) {
super();
this.name = name;
this.email = email;
this.gender = gender;
}
public String toString()
{
return "Name :-" +name+" email "+email+" gender "+gender;
}

}
package com.suraj.programs;

public class Book


{
String name;
Author author;
double price;
int qtyInStock;
public Book(String name, Author author, double price, int qtyInStock) {
super();
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQtyInStock() {
return qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}

}
package com.suraj.programs;

public class AuthorMain {

public static void main(String[] args) {


Author a=new Author("suraj","[email protected]",'M');
Book b=new Book("Java ",a,500,100);
b.getAuthor();
System.out.println("book name "+b.getName());;
System.out.println("Author "+b.getAuthor());
System.out.println("Price "+b.getPrice());;
System.out.println("Quntity "+b.getQtyInStock());

}
}
Output:- book name Java
Author Name:-suraj email [email protected] gender M
Price 500.0
Quntity 100
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q10. Create a class named Animal which includes method like eat() and sleep().
Create a child class of Animal named Bird and override the parent class methods.
Add a new method named fly().
Create an instance of Animal class and invoke the eat and sleep method using this
object.
Create an instance of Bird class and invoke the eat, sleep and fly method using this
object
Program:-

package com.suraj.Inheritance;

public class Animal


{
public void eat()
{
System.out.println("Animal Eat");
}
public void sleep()
{
System.out.println("Animal sleep");
}
}
package com.suraj.Inheritance;

public class Bird


{
public void eat()
{
System.out.println("Bird Eat insects and seeds");
}
public void sleep()
{
System.out.println("Bird sleep");
}
public void fly()
{
System.out.println("Bird can fly ");
}
}

package com.suraj.Inheritance;

public class AnimalMainClass {

public static void main(String[] args) {


Animal a=new Animal();
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

a.eat();
a.sleep();
Bird b=new Bird();
b.eat();
b.sleep();
b.fly();

}
Output:-
Animal Eat
Animal sleep
Bird Eat insects and seeds
Bird sleep
Bird can fly

Q11. Create a class Person with a member variable name. Save it in a file called
Person.java. Create a class called Employee that will inherit the Person class. The other
data members of the Employee class are annual salary (double), the year the employee
started to work, and the national insurance number.

Your class should have the necessary constructors and getter / setter methods.
Create another class called TestEmployee containing a main method to fully test your class
definition.

Program:-

package com.suraj.Employee;

public class Person


{
String name;

public Person(String name) {


super();
this.name = name;
}

}
package com.suraj.Employee;

public class Employee extends Person


{
double salary;
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

int year;
int ins_num;
public Employee(String name, double salary, int year, int ins_num) {
super(name);
this.salary = salary;
this.year = year;
this.ins_num = ins_num;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getIns_num() {
return ins_num;
}
public void setIns_num(int ins_num) {
this.ins_num = ins_num;
}

package com.suraj.Employee;

public class TestEmployee


{
public static void main(String[] args)
{
Employee e=new Employee("Suraj",50000,2009,1234);

System.out.println("Name "+e.name);
System.out.println(e.getSalary());
System.out.println(e.getYear());
System.out.println(e.getIns_num());

}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Output:- Name Suraj


50000.0
2009
1234

Q12. Write a java code to calculate simple interest using constructor overloading.

Program:-

import java.util.Scanner;

class SI
{
float p,r,t;
SI()
{
p=0.0f;
r=0.0f;
t=0.0f;

public SI(float p, float r, float t) {


this.p = p;
this.r = r;
this.t = t;
}

void cal()
{
float si = (r * t * p) / 100;
System.out.println("Simple interest on amount "+p+"is "+si);
}

}
public class SimpleInterest {
public static void main(String args[])
{
SI os=new SI(2000,10,1);
os.cal();
}
}

Output:- Simple interest on amount 2000.0is 200.0


Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q13. Write a java code to find area of triangle ,square and rectangle using method
overloading.

Program:-
import java.util.Scanner;
class Overloading
{
int area(int x)
{
return (x*x); //AREA OF SQUARE
}
int area(int l,int b)
{
return (l*b); //AREA OF RECTANGLE
}
double area(double h,double b)
{
return (0.5*h*b); //AREA OF TRIANGLE
}
double area(double r)
{
return (3.14*r*r); //AREA OF CIRCLE
}

class Over
{
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);


Overloading obj=new Overloading();

System.out.println("\nEnter side for calculating area of Square:");


int n=sc.nextInt();
System.out.println("\nArea of Square:"+obj.area(n));

System.out.println("\nEnter lenght and breadth for calculating area of


Rectangle:");
int l=sc.nextInt();
int b=sc.nextInt();
System.out.println("\nArea of Rectangle:"+obj.area(l,b));
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

System.out.println("\nEnter height and base for calculating area of


Triangle:");
double h=sc.nextDouble();
double t=sc.nextDouble();
System.out.println("\nArea of Triangle:"+obj.area(h,t));

System.out.println("\nEnter radius for calculating area of Circle:");


double r=sc.nextDouble();
System.out.println("\nArea of Circle:"+obj.area(r));

}
}

OUTPUT:
Enter side for calculating area of Square:
5
Area of Square:25
Enter lenght and breadth for calculating area of Rectangle:
2
3
Area of Rectangle:6
Enter height and base for calculating area of Triangle:
4.1
3.1
Area of Triangle:6.3549999999999995
Enter radius for calculating area of Circle:
2
Area of Circle:12.56

Q14. Inheritance:- Write a java code to create a class Account and two other classes
Current and Savings that extends Account class.

Program:-
import java.util.Scanner;

class Acc_In
{
int accno;
String name;
double balance;
void getData()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter account number");
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

accno=sc.nextInt();
System.out.println("Enter name ");
name=sc.next();
System.out.println("Enter amount ");
balance=sc.nextDouble();

}
void display()
{
System.out.println("account number"+accno);
System.out.println("name of customer is "+name);
System.out.println("Balance "+balance);
}
}
class Current extends Acc_In
{
void withdarw()
{
System.out.println("Enter amount to withdraw");
int amt=new Scanner(System.in).nextInt();
if(amt>balance)
{
balance=balance-amt;
}

}
void deposite()
{
System.out.println("Enter amount to deposite");
int amt=new Scanner(System.in).nextInt();

balance=balance+amt;
}

}
class Saving extends Acc_In
{
void withdarw()
{
System.out.println("Enter amount to withdraw");
int amt=new Scanner(System.in).nextInt();
if(amt>balance)
{
balance=balance-amt;
}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

}
void deposite()
{
System.out.println("Enter amount to deposite");
int amt=new Scanner(System.in).nextInt();

balance=balance+amt;
}

}
public class AccountInheritance {
public static void main(String[] args)
{
Current oc=new Current();
Saving os=new Saving();
oc.getData();
oc.deposite();
oc.withdarw();
oc.display();
os.getData();
os.deposite();
os.withdarw();
os.display();
}

}
Output:
Enter account number
3000
Enter name
Suraj
Enter amount
300
Enter amount to deposite
104
Enter amount to withdraw
32
account number3000
name of customer is Suraj
Balance 404.0
Enter account number
123
Enter name
Negi
Enter amount
50000
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Enter amount to deposite


2000
Enter amount to withdraw
200
account number 221
name of customer is Suraj Negi
Balance 62000.0

Q15. Write a java code to compute area of rectangle , square ,triangle using the concept of
abstract class and overriding.

Program:-
class Shape
{
double area;
int r,l,h;
Shape(int r,int l ,int h)
{
this.r=r;
this.l=l;
this.h=h;
}
void area()
{
System.out.println("Area to be calculat");
}
}
class Square extends Shape
{
Square(int a,int b,int c)
{
super(a,b,c);
}
void area()
{
System.out.println("area of rectangle"+(l*l)); //AREA OF
SQUARE
}

}
class Rect extends Shape
{
Rect(int a,int b,int c)
{
super(a,b,c);
}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

void area()
{
System.out.println("Area of rectangle"+l*h); //AREA OF
RECTANGLE
}

}
class Triangle extends Shape
{
Triangle(int a,int b,int c)
{
super(a,b,c);
}
void area()
{
System.out.println("Area of Triangle "+(0.5*l*h)); //AREA OF
TRIANGLE
}
}

public class MethodOverriding


{
public static void main(String[] args)
{
Square sq=new Square(2,2,2);
Rect r=new Rect(2,4,5);
Triangle tri=new Triangle(2,3,4);
sq.area();
r.area();
tri.area();

}
Output:
area of rectangle4
Area of rectangle20
Area of Triangle 6.0
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q16. Write a java code to create Thread and show the working of yield() and sleep method.

Program:-
class One extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
if(i==1) yield();
System.out.println("From One "+i);
}

System.out.println("Exit From One ");


}
}
class Two extends Thread
{
public void run()
{
for(int k=1;k<5;k++)
{
try
{
if(k==2)
sleep(1000);
}
catch(Exception e)
{
}
System.out.println("From Two "+k);
}

System.out.println("Exit From Two ");


}
}
class Three extends Thread
{
public void run()
{
for(int j=1;j<5;j++)
{

System.out.println("From Three "+j);


try
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

{
if(j==2)
{
stop();
}
}
catch(Exception e)
{
}
}

System.out.println("Exit From Three ");


}
}
class ThreadLife
{
public static void main(String args[])
{
One o=new One();
Two t=new Two();
Three th=new Three();
th.setPriority(Thread.MAX_PRIORITY);
t.setPriority(o.getPriority()+1);
o.setPriority(Thread.MIN_PRIORITY);

System.out.println("Start Thread One");


o.start();
System.out.println("Start Thread TwO");
t.start();
System.out.println("Start Thread Three");
th.start();
}
}

Output:-

D:\javadata>java ThreadLife
Start Thread One
Start Thread TwO
From One 1
From Two 1
Start Thread Three
From One 2
From One 3
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

From Three 1
From Three 2
From One 4
Exit From One
From Two 2
From Two 3
From Two 4
Exit From Two

Q17. Write a java code to implement synchronized method

Program:-
class Pyra
{
synchronized void dis(char c)
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=i;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}
class A extends Thread
{
Pyra p;
A(Pyra p)
{
this.p=p;
}
public void run()
{
p.dis('*');
}
}
class B extends Thread
{
Pyra p;
B(Pyra p)
{
this.p=p;
}
public void run()
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

{
p.dis('#');
}
}
class Thsyn
{
public static void main(String args[])
{
Pyra p=new Pyra();
A ta=new A(p);
B tb=new B(p);
ta.start();
tb.start();

}
}
Output:

D:\javadata>javac Thsyn.java

D:\javadata>java Thsyn
*
**
***
****
*****
#
##
###
####

Q18. Write a program to remove duplicate elements .

Program:-
public class RemoveElement
{
public static int removeDuplicateElements(int arr[], int n)
{
if (n==0 || n==1){
return n;
}
int[] temp = new int[n];
int j = 0;
for (int i=0; i<n-1; i++){
if (arr[i] != arr[i+1]){
temp[j++] = arr[i];
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

}
}
temp[j++] = arr[n-1];
// Changing original array
for (int i=0; i<j; i++){
arr[i] = temp[i];
}
return j;
}

public static void main (String[] args) {


int arr[] = {10,20,20,30,30,40,50,50};
int length = arr.length;
length = removeDuplicateElements(arr, length);
//printing array elements
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
}
Output:-
D:\programming> javac RemoveElement.java
D:\programming>java RemoveElement
10 20 30 40 50
Q19. Write a program to print the sum of the elements of an array following the given
condition
If the array has 6 and 7 in succeeding orders, ignore the numbers between 6 and 7
consider the other numbers for calculation of sum.

Program:-
class Removebetween6and7
{

public static void main (String[] args)


{
int n[] = {1,6,2,3,7,4,5};
int flag=0;
int sum=0;
outer:
for (int i = 0; i < n.length; i++)
{
if (n[i] == 6)
{
for (int j = i + 1; j < n.length; j++)
{
if (n[j] == 7)
{
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

i = j;
continue outer;
}
}
}
sum += n[i];
}

System.out.println(sum);
}

}
Output:- 10
Q20. Write a java program to create a file named abc.txt and write content in the file.

Program:-
import java.io.*;
class PrintDemo
{
public static void main(String[] args)
{
try
{
FileWriter fw=new FileWriter("abc.txt");
PrintWriter pw=new PrintWriter(fw);
pw.write(100);//d
pw.println(100);//100
pw.print(true);
pw.println('H');
pw.println("Suraj");
fw.flush();
pw.close();
}
catch (IOException e)
{
}
System.out.println("Hello World!");
}
}
Output:- File created in current working directory with following content
d100
trueH
Suraj
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q21. Write a java program to demonstrate object serialization and deserialization . Create
a file notes.ser and save state of an instance.

Program:-
import java.io.*;
class Student implements Serializable
{
String name;
int roll;
Student(String name, int roll)
{
this.name=name;
this.roll=roll;
}
}
class SerDemo
{
public static void main(String[] args)
{
try
{
Student st=new Student("Suraj",63);
FileOutputStream fos=new FileOutputStream("notes.ser");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(st);
System.out.println("Obect state saved");
FileInputStream fis=new FileInputStream("notes.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
Student st2=(Student)ois.readObject();
System.out.println(st2.name+" and the roll is "+st2.roll);
}
catch (IOException io)
{
io.printStackTrace();
}
catch (ClassNotFoundException io)
{
io.printStackTrace();
}

}
}
Output:-
Suraj and roll number is 63
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q22. Write a java program to count characters in string


Program:-
class CountCharacterInString
{
public static void main(String[] args)
{

String str="abcdefG";

System.out.println("="+getSum(str));
}
static int getSum(String str)
{
int c=1;
int s=0;
for(int i=0;i<str.length();i++)
{
System.out.print(" "+str.charAt(i));

s=s+c;
//c++;
}
return s;
}
}
Output:- D:\programming>java CountCharacterInString
a b c d e f G=7

Q23. Write a java program to demonstrate the working of equals() method with String
class and StringBuffer class instance.

Program:-

class DemoString
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer("abc");
StringBuffer sb2=new StringBuffer("abc");
System.out.println(sb1.equals(sb2));//false
String s1=new String("abc");
String s2=new String("abc");
System.out.println(s1.equals(s2));//true
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

}
}

Output:-
false
true
Q24. Write a java program to insert a new string in specified position of existing String.

Program:-

class InsertS
{
public static void main(String[] args)
{
String str1="Helloworld";
String str2="GREAT";
int pos=5;
System.out.println(str1);
System.out.println(str2);
String str3=new String();
for(int i=0;i<str1.length();i++)
{
str3=str3+str1.charAt(i);
if(i==pos-1)
{
str3=str3+str2;
}
}
System.out.println(str3);
}
}
Output:-

D:\programming>javac InsertS.java

D:\programming>java InsertS
Helloworld
GREAT
HelloGREATworld

Q25. Create a GUI application using applet to add textfield values.

Program:-
import java.applet.Applet;
import java.awt.*;
public class AppAdd extends Applet
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

{
TextField t1,t2;
public void init()
{
t1=new TextField(8);
t2=new TextField(8);
add(t1);
add(t2);
}
public void paint(Graphics g)
{
int n=0,m=0,r=0;
String s1;
try
{
n=Integer.parseInt(t1.getText());
m=Integer.parseInt(t2.getText());
}
catch(Exception e)
{}
r=n+m;
g.drawString("Sum of two integers",100,200);
s1=String.valueOf(r);
g.drawString(s1,150,250);
}
}
AppAdd.html
<html>
<applet code=AppAdd.class height =400 width=400>
</applet>
</html>
Output:
D:\javadata>javac AppAdd.java
D:\javadata>appletviewer AppAdd.html
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q26. Create a GUI login application using swing.

Program:-
package advanceJava;
import java.awt.event.*;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import java.sql.*;

class LoginClass extends JFrame implements ActionListener{


JLabel unPrompt, pwPrompt;
JTextField unameF;
JPasswordField pswF;
JButton button;

LoginClass(){
JFrame jFrame = new JFrame("Login Form");

unPrompt = new JLabel("Enter Username:");


unPrompt.setBounds(80,70,200,30);
jFrame.add(unPrompt);
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

unameF = new JTextField(10);


unameF.setBounds(200,70,200,30);
jFrame.add(unameF);

pwPrompt = new JLabel("Enter Password:");


pwPrompt.setBounds(80,110,200,30);
jFrame.add(pwPrompt);

pswF = new JPasswordField(10);


pswF.setBounds(200,110,200,30);
jFrame.add(pswF);

button = new JButton("Login");


button.setBounds(300,160,100,30);
jFrame.add(button);

jFrame.setSize(500, 300);
jFrame.setLayout(null);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

button.addActionListener(this);
}

public void actionPerformed(ActionEvent ae){


try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String username = unameF.getText();
String password = pswF.getText();

//Connection creation
Connection con=null;
try {
con =
DriverManager.getConnection("jdbc:mysql://localhost:3309/graphic", "root", "root");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Statement st=null;
try {
st = con.createStatement();
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

} catch (SQLException e1) {


// TODO Auto-generated catch block
e1.printStackTrace();
}

//Query processing
ResultSet rs=null;
try {
rs = st.executeQuery("select * from login where username =
'"+username+"'");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try{
rs.next();
String dbUname = rs.getString("username");
if(password.equals(rs.getString("password"))){
JLabel j3 = new JLabel("Authentication successful..");
add(j3);
} else{
JLabel j4 = new JLabel("wrong password..");
add(j4);
}
} catch(SQLException e){
JLabel j5 = new JLabel("Authentication successful..");
add(j5);
} catch(Exception e){
e.printStackTrace();
}
}
}

public class Login{


public static void main(String... args){
LoginClass l = new LoginClass();
}
}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q27. Write a java code to establish connection with database

Program:-

import java.sql.*;
import java.util.Scanner;
public class FetchData {
public static void main(String[] args)throws Exception
{
Scanner sc=new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/graphic","root","root");
System.out.println("Connection established");
}
}

Output:-

Connection established
BUILD SUCCESSFUL (total time: 1 second)

Q28. Write a java code to fetch records from student table

Program:-

package datafetch;
import java.sql.*;
public class Datafetch {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/testing";
String usr="root";
String psw="root";
Connection con=DriverManager.getConnection(url, usr, psw);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student");
rs.next();
String name=rs.getString(2);
int r=rs.getInt(1);
System.out.println("name of student is "+name);
System.out.println("Roll number is "+r);

}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

}
Output:-
run:
name of student is ajay
Roll number is 1
BUILD SUCCESSFUL (total time: 0 seconds)

Q29. Write a java code to insert records into table

Program:-

package mca4seca;
import java.sql.*;
import java.util.Scanner;
public class MultipledataInsert {
public static void main(String[] args)throws Exception

{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/graphic","root","root");
String str="insert into employ values(?,?,?)";
PreparedStatement pst=con.prepareStatement(str);
System.out.println("Enetr npo of records");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int id=0;
String name=null;
double salary=0.0;
while(n>0)
{
System.out.println("Enter unique id ");
id=sc.nextInt();
System.out.println("Enter name ");
name=sc.next();
System.out.println("Enter salary ");
salary=sc.nextDouble();
pst.setInt(1, id);
pst.setString(2, name);
pst.setDouble(3, salary);
pst.executeUpdate();
n--;
}

System.out.println("Data inserted succesfully");


}
}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Output:
Enetr npo of records
2
Enter unique id
001
Enter name
aaa
Enter salary
222
Enter unique id
002
Enter name
www
Enter salary
343
Data inserted succesfully
BUILD SUCCESSFUL (total time: 21 seconds)

Q30 Write a JDBC code to delete record from table

Program:-

package mca4seca;
import java.sql.*;
import java.util.Scanner;
public class DeleteRow {

public static void main(String[] args)throws Exception


{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/graphic";
String usr="root";
String psw="root";
Class.forName(driver);
Connection con=DriverManager.getConnection(url,usr,psw);
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
System.out.println("Enetr employ salary for row deletion");
double sal=sc.nextDouble();
String q=String.format("delete from employ where salary>=%f", sal);
int count=st.executeUpdate(q);
System.out.println("Number of row deleted "+count );

}
}
Output
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

run:
Enetr employ salary for row deletion
222
Number of row deleted 9
BUILD SUCCESSFUL (total time: 4 seconds)

Q31. Write a JDBC program to perform following operations


rs.first()
rs.last()
rs.absolute(n)

Program:-

package datafetch;
import java.sql.*;
public class Datafetch {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/testing";
String usr="root";
String psw="root";
Connection con=DriverManager.getConnection(url, usr, psw);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student");
rs.first();
String name=rs.getString(2);
int r=rs.getInt(1);
System.out.println("name of student is "+name);
System.out.println("Roll number is "+r);
rs.last();
String name=rs.getString(2);
int r=rs.getInt(1);
System.out.println("name of student is "+name);
System.out.println("Roll number is "+r);
rs.absolute(6);
String name=rs.getString(2);
int r=rs.getInt(1);
System.out.println("name of student is "+name);
System.out.println("Roll number is "+r);

}
Output:
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

run:
name of student is ajay
Roll number is 1
name of student is Don
Roll number is 10
name of student is John
Roll number is 6

BUILD SUCCESSFUL (total time: 0 seconds)


Q32. Write a JDBC program to demonstrate batch update.

Program:-
package advanceJava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

publicclass BatchUpdate {

publicstaticvoid main(String[] args) {


Connection con = null;
Statement st = null;
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/test";
final String USERNAME = "root";
final String PASSWORD = "root";
try {
Class.forName(DRIVER_CLASS);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
st = con.createStatement();

String qr= "insert into student values (13, 'Vipul', 'F')";


st.addBatch(qr);

qr = "update student set grades='F' where grades='D'";


st.addBatch(qr);;

qr = "delete from student where grades = 'F'";


st.addBatch(qr);

int[] affectedRows = st.executeBatch();

System.out.println("Rows affected...");
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

System.out.println("Query 1: "+affectedRows[0]+", Query 2:


"+affectedRows[1]+", Query 3: "+affectedRows[2]);

}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(st!=null || con!=null) {
try {
con.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
}

Output:

Rows affected...
Query 1: 1, Query 2: 1, Query 3: 3

Q33. Write a JDBC program to demonstrate ResultSetMetaData

Program:-

package advanceJava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

publicclass RSMetaData {

publicstaticvoid main(String[] args) {


Connection con = null;
Statement st = null;
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/test";
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

final String USERNAME = "root";


final String PASSWORD = "root";
try {
Class.forName(DRIVER_CLASS);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
st = con.createStatement();

String query = "select * from student";


ResultSet rs = st.executeQuery(query);
ResultSetMetaData rsMetaData = rs.getMetaData();

System.out.println("Total columns: "+rsMetaData.getColumnCount());


System.out.println("2nd Column name:
"+rsMetaData.getColumnName(2));
System.out.println("2nd Column data type:
"+rsMetaData.getColumnTypeName(2));

rs.close();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(st!=null || con!=null) {
try {
con.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
}

}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

//Output:

Total columns: 3
2nd Column name: sname
2nd Column data type: VARCHAR
Q34. Program to show use of CallableStatement without any parameters

Program:-

/**MySQL**/
mysql> delimiter /
mysql>
mysql> create procedure disp()
-> begin
-> select * from student;
-> end
-> /
Query OK, 0 rows affected (0.40 sec)

mysql> call disp()/


+-----+----------+--------+
| sid | sname | grades |
+-----+----------+--------+
| 1 | Anu |A |
| 3 | Kale | B |
| 4 | Kale | C |
| 5 | Doe |B |
| 8 | Aradhana | A |
| 10 | jack | B |
| 11 | ducky | C |
+-----+----------+--------+
7 rows in set (0.00 sec)

Query OK, 0 rows affected (0.02 sec)


Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

package advanceJava;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

publicclass CallableNoArgs {

publicstaticvoid main(String[] args) {


Connection con = null;
CallableStatement cst = null;
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/test";
final String USERNAME = "root";
final String PASSWORD = "root";
try {
Class.forName(DRIVER_CLASS);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);

cst = con.prepareCall("{call disp()}");


cst.execute();

System.out.println("Procedure executed sucessfully...");


}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(cst!=null || con!=null) {
try {
con.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

//Output:

Procedure executed sucessfully...

Q35 Program to show use of CallableStatement with IN parameter

Program:-
mysql> create procedure deleteSid(IN studId int)
-> begin
-> delete from student where sid = studId;
-> end
-> /
Query OK, 0 rows affected (0.00 sec)

mysql> select * from student;


-> /
+-----+----------+--------+
| sid | sname | grades |
+-----+----------+--------+
| 1 | Anu |A |
| 3 | Kale | B |
| 4 | Kale | C |
| 5 | Doe |B |
| 8 | Aradhana | A |
| 10 | jack | B |
| 11 | ducky | C |
+-----+----------+--------+
7 rows in set (0.00 sec)

mysql>
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

package advanceJava;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;

publicclass CallableNoArgs {

publicstaticvoid main(String[] args) {


Connection con = null;
CallableStatement cst = null;
final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/test";
final String USERNAME = "root";
final String PASSWORD = "root";
Scanner sc = new Scanner(System.in);
try {
Class.forName(DRIVER_CLASS);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);

cst = con.prepareCall("{call deleteSid(?)}");

System.out.print("Enter sid to delete: ");


intid = sc.nextInt();

cst.setInt(1, id);
cst.executeUpdate();
System.out.println("Deleted successfully..");
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(cst!=null || con!=null) {
try {
con.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
}

}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

//Output:

Enter sid to delete: 5


Deleted successfully..

/**MySQL*/

mysql> select * from student/


+-----+----------+--------+
| sid | sname | grades |
+-----+----------+--------+
| 1 | Anu |A |
| 3 | Kale | B |
| 4 | Kale | C |
| 8 | Aradhana | A |
| 10 | jack | B |
| 11 | ducky | C |
+-----+----------+--------+
6 rows in set (0.00 sec)

Q36 :- Implements a service() mtehod of Servlet

Program:-

Index.html:-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="Add" method="post">
Enter first number <input type="text" name="t1">
<br>
<br>
Enter Second number <input type="text" name="t2">
<br>
<br>
<input type="submit" name="b1"></form>

</body>
</html>
Add.java:-
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

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 Add extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException
{
int i=Integer.parseInt(req.getParameter("t1"));
int j=Integer.parseInt(req.getParameter("t2"));
int r=i+j;
PrintWriter pw=res.getWriter();
pw.print("Addition of two integers"+r);}
}
Output:-

Index.html

On successful Add.java servlet will called by web container and following page will open
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q37. Create a web application which shows difference between doGet() and doPost()
method

Program:-

Index.html:-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="Add" method="post">
//<form action=”Add” method =”get”>
Enter first number <input type="text" name="t1">
<br>
<br>
Enter Second number <input type="text" name="t2">
<br>
<br>
<input type="submit" name="b1"></form>

</body>
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

</html>
Add.java:-
package postpkg;

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;
import java.io.PipedWriter;
public class PostorGet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException
{
process(req,res);
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException
{
process(req,res);
}
public void process(HttpServletRequest req,HttpServletResponse res)throws IOException
{
int i=Integer.parseInt(req.getParameter("t1"));
int j=Integer.parseInt(req.getParameter("t2"));
int c=i+j;
PrintWriter pw=res.getWriter();
pw.println("Addition of two integers "+c);
}

}
Output:-
Index.html
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

On successful Add.java servlet will called by web container and following page will open

Q38. Create a web application which redirec the request from one servlet two another
servlet

Program:-
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="FirstServlet" >
<form action="Add" method="post">
Enter any number <input type="text" name="t1">
<br>
<input type="submit" value="ok">
</form>
</body>
</html>
FirstServlet.java
package midreqdis;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {

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


ServletException
{
RequestDispatcher rd=req.getRequestDispatcher("SecondServlet");
rd.include(req, res);

}
}
SecondServlet.java
package midreqdis;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

public class SecondServlet extends HttpServlet {

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


{
int f=1;

int n=Integer.parseInt(req.getParameter("t1"));
while(n>0)
{
f=f*n;
n--;
}
PrintWriter out=res.getWriter();
out.println("Hello from Second Servlet and factorial of number is"+f);
}
}
Output:-
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q39. Implements a Servlet life cycle .

Program:-

Index.html:-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="FirstServlet" method="post">
<input type="submit" name="b1"></form>

</body>
</html>
LifeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LifeServlet extends HttpServlet {
int i;
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

public void init()


{
i=1;
System.out.println("from init");
}
public void service(HttpServletRequest req,HttpServletResponse res) throws IOException
{
PrintWriter pw=res.getWriter();
pw.println("total vivitors"+i);
i++;
System.out.println("From service");
}
public void destroy()
{
System.out.println("From destroy");
}
}
Output:-

Apache log:-

from init
From service
From service
From service
From service
Feb 23, 2017 4:57:37 PM org.apache.coyote.http11.Http11AprProtocol pause
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

INFO: Pausing Coyote HTTP/1.1 on http-8080


Feb 23, 2017 4:57:37 PM org.apache.coyote.ajp.AjpAprProtocol pause
INFO: Pausing Coyote AJP/1.3 on ajp-8009
Feb 23, 2017 4:57:38 PM org.apache.catalina.core.StandardService stop
INFO: Stopping service Catalina
Feb 23, 2017 4:57:39 PM org.apache.coyote.http11.Http11AprProtocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8080
Feb 23, 2017 4:57:39 PM org.apache.coyote.ajp.AjpAprProtocol destroy
INFO: Stopping Coyote AJP/1.3 on ajp-8009
From destroy
Index.html

Q40. Create a Login application using Servlet and Java database connectivity.

Program:-

Index.html:-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body bgcolor="yellow">
<h1>Hello World!</h1>
<form action="Login" method="post">
<table border =2>
<tr>
<td> Enter User Name</td><td><input type="text" name="t1"></td></tr>
<br>
<tr><td>Enter Password</td><td><input type="password" name="t2"></td></tr>
<br>
</table>
<input type="submit" value="Login">
</body>
</html>

Login.java:-
package loginpkg;

import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
public class Login extends HttpServlet
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

public void service(HttpServletRequest req,HttpServletResponse res)


{
try
{
Check(req,res);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void Check(HttpServletRequest req,HttpServletResponse res)throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from admin");
rs.next();
String str1=rs.getString(1);
String str2=rs.getString(2);
String str3=req.getParameter("t1");
String str4=req.getParameter("t2");
PrintWriter pw=res.getWriter();
if((str1.equals(str3))&&(str2.equals(str4)))
{

pw.println("Login Success");
try{
PrintWriter pw1=res.getWriter();
pw1.println("Welcome "+str1);

}
catch(Exception e)
{
e.printStackTrace();
}

}
else
{
pw.println("something goes wrong please relogin");
}

}
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

}
Output:-

Index.html

On successful Login.java servlet will called by web container and following page will open
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Q41. Develop a jsp application to display student record. User input student_id to jsp file.
In case student_id does not exist, show error message otherwise show details

Program:-

User Form

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


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
</head>
<body>
<div style="background: gray;margin-top:100px">
<center>
<h1>USER FORM</h1>
<form action="TermWork19.jsp">
<h2>Student ID</h2><input type="text" name="id" style="text-align:center"></br>
<h2><input type="submit" name="submit"></h2>
</form>
</center>
</div>
</body>
</html>
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

Action Page

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


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>show records</title>
</head>
<body>
<%int id=Integer.parseInt(request.getParameter("id"));%>
<%Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/javat","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student where id="+id+"");
if(rs.next())
{%>
<jsp:forward page="Term19Show.jsp?id=<%=id%>"></jsp:forward>
<%}
else
{%>
<jsp:include page="TermWork19StuForm.jsp"></jsp:include>
<h2>invalid id</h2>
<%}
%>
</body>
</html>
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

User Info Page

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


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>show</title>
</head>
<%int id=Integer.parseInt(request.getParameter("id")); %>
<%Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/javat","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student where id="+id+"");
rs.next();
%>
<body>
<div style="background: gray;margin-top:100px">
<center>
<h1>USER Info</h1>
<form>
<h2>ID</h2><input type="text" value="<%=rs.getString("id")%>" style="text-
align:center"></br>
<h2>Name</h2><input type="text" value="<%=rs.getString("name")%>" style="text-
align:center"></br>
<h2>Student ID</h2><input type="text" value="<%=rs.getString("class")%>" style="text-
align:center"></br>
<h2>Email</h2><input type="text" value="<%=rs.getString("email")%>" style="text-
align:center"></br>
</form>
</center>
</div>
</body>
</html>
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

OUTPUT
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63

of jsp:include and jsp:forward )

You might also like