Surajjava 1
Surajjava 1
: -63
Q1. Write a java program to calculate sum of last digits of two numbers.
Program:-
Program:-
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
Program:-
class TestCyclic
{
public static void main(String[] args)
{
System.out.println(cyclic(12345));
}
return sum;
}}
Output: - 55
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
Example 1-
input1=123
input2=582
input3=175
Example 2-
input1=190
input2=267
input3=853
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 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
}
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)
{
}
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
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;
}
package com.suraj.programs;
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;
}
}
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;
package com.suraj.Inheritance;
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;
}
package com.suraj.Employee;
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;
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
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;
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();
}
}
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)
{
}
}
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
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
}
}
}
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);
}
{
if(j==2)
{
stop();
}
}
catch(Exception e)
{
}
}
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
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
*
**
***
****
*****
#
##
###
####
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;
}
Program:-
class Removebetween6and7
{
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
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
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
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.*;
LoginClass(){
JFrame jFrame = new JFrame("Login Form");
jFrame.setSize(500, 300);
jFrame.setLayout(null);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
}
//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
//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();
}
}
}
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)
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)
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--;
}
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)
Program:-
package mca4seca;
import java.sql.*;
import java.util.Scanner;
public class DeleteRow {
}
}
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)
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
Program:-
package advanceJava;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
publicclass BatchUpdate {
System.out.println("Rows affected...");
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63
}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
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 {
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)
package advanceJava;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
publicclass CallableNoArgs {
//Output:
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>
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 {
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:
/**MySQL*/
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;
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;
}
}
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
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
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
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
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
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
Action Page
OUTPUT
Name: - Suraj Singh Negi Course: -MCA 2nd Sem/Section B Roll No.: -63