Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
58 views

071 Java Journal

The document contains code snippets that demonstrate inheritance and polymorphism in Java. It defines an abstract Vehicle class with a passenger variable and check() method. Concrete Car and Bus classes extend Vehicle and override check() to return the number of passengers. The main method creates Car and Bus objects and calls check() to display the passengers for each. It also defines a Company class with name and employee variables. ITCompany and NonITCompany extend Company and override the constructor to display company-specific details. The main method demonstrates inheritance by creating objects of the subclasses.

Uploaded by

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

071 Java Journal

The document contains code snippets that demonstrate inheritance and polymorphism in Java. It defines an abstract Vehicle class with a passenger variable and check() method. Concrete Car and Bus classes extend Vehicle and override check() to return the number of passengers. The main method creates Car and Bus objects and calls check() to display the passengers for each. It also defines a Company class with name and employee variables. ITCompany and NonITCompany extend Company and override the constructor to display company-specific details. The main method demonstrates inheritance by creating objects of the subclasses.

Uploaded by

CR 7
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

____________________________________________________

Abstract Class
Q1. Create an abstract class Vehicle with a member variable no-of
passengers and a member function check () that displays the number
of passengers. Create two subclasses Car and Bus that’s extends the
abstract class. Display the number of passengers for Car and Bus.

Answer:
import java.util.*;
abstract class Vehincle
{
int no_of_passenger;

abstract int Check();

}
class Car extends Vehincle
{
public int Check()
{
int no_of_passenger= 10;

return no_of_passenger;

}
}
class Bus extends Vehincle
{
public int Check()
{
int no_of_passenger=20;

return no_of_passenger;

}
}
abstract class Slip_one
{
public static void main(String [] args)
{
Vehincle v;
v = new Car();
System.out.println("Number of passengers are:"+v.Check());
v = new Bus();
System.out.println("Number of passengers are:"+v.Check());
}
}

OUTPUT:
Numbers of passengers are: 10
Numbers of passengers are: 20
______________________________________________________________________________

Package
Q2. Create a package named Sequence having two different classes
to print the following series: a) Factorial of numbers
b) Squares of numbers
Write a program to generate ‘n’ terms of above sequence.
Answer:
a) Factorial of numbers
1].Fact.java
package name_sequence;
import java.util.*; public
class fact
{
public void show()
{
int f=1,n2=1,n3,i=0,n=0;
Scanner sc= new Scanner(System.in);

System.out.println("Enter value of n:");

n=sc.nextInt();

for(i=2;i<=n;i++)

{
f=f*i;
}
System.out.println(" "+f);
}
}
Importing package:
import name_sequence.fibbo;
class xyz
{
public static void main(String [] args)
{
fibbo f = new fibbo();
f.show();
}
}

OUTPUT:
C:\Users\Faizan\Desktop\Java_Practicle>cd name_*

C:\Users\ Faizan \Desktop\Java_Practicle\name_sequence>javac fibbo.java

C:\Users\ Faizan \Desktop\Java_Practicle\name_sequence>cd..

C:\Users\ Faizan \Desktop\Java_Practicle>javac Slip22.java

C:\Users\ Faizan \Desktop\Java_Practicle>java Slip22 Enter


value of n:
3
6
______________________________________________________________________________

b) Squares of numbers

2]squr.java package
Slip_two;
import java.util.*; public
class squr

{
public void show1()
{
//int x =1;
int n1;
Scanner sc= new Scanner(System.in);
System.out.println("Enter value of n1:");
n1=sc.nextInt(); for(int i=1;i<=n1;i++)
{
//x = ((i));
System.out.println("Square is: "+(i*i));
}
}
}
Importing package
import
slip_two.squr; class
abc
{
public static void main(String [] args)
{
squr s = new squr();
s.show1();
}
}

OUTPUT:
Enter value of n1:
5
Square is: 1
Square is: 4
Square is: 9
Square is: 16
Square is: 25
______________________________________________________________________________

Array of
Object
Q3. Write a java program for a cricket player object. The program
should accept details of ‘n’ players from user. The details of player are
Player name, runs, innings-played. The program should contain
following menu options enter details of player, display average runs
of single player, sort names of players based on number of runs. Use
array of object and function overloading

Answer:
import java.io.*;
import java.util.*; class
Player
{
int run;
String name;
int pd; void
accept()
{
Scanner scan=new Scanner(System.in);

System.out.println("Enter player name");

name=scan.next();
System.out.println("Enter run");

run=scan.nextInt();

System.out.println("Enter no of innings-played");
pd=scan.nextInt();
}
void average ()
{
double avg=0; avg+=(double)run/(double)pd;
System.out.println("Name of player= "+name);
System.out.println("average of player= "+avg);
System.out.println();
}
}
class Cricket
{
public static void main(String args[])
{ int
i;
Scanner scan=new Scanner(System.in);
System.out.println("Enter how many players want");
int n=scan.nextInt();
Player s[]=new Player[n];
;
for(;;)
{
System.out.println("1.Enter details of player ");
System.out.println("2.Display average runs ");
System.out.println("3. EXIT...");
System.out.println("Enter your choice");

int ch = scan.nextInt();
switch(ch)
{
case 1:
for(i=0;i<n;i++)
{
s[i]=new Player(); //allocation

s[i].accept(); //call function

}
break;
case 2:
for(i=0;i<n;i++)
{
s[i].average();
}
break;
case 3:
break;

}
}
}
}

OUTPUT:
D:\Javaprog\lab>java Cricket
Enter how many players want
2
1. Enter details of player
2. Display average runs
3. EXIT...
Enter your choice
1
Enter player name
Shubham
Enter run
12000
Enter no of innings-played
12
Enter player name
Shantanu
Enter run
1000
Enter no of innings-played
12
1. Enter details of player
2. Display average runs
3. EXIT...
Enter your choice
2
Name of player= shubham average of
player= 1000.0 Name of player=
shantanu average of player=
83.33333333333333
1. Enter details of player
2. Display average runs
3. EXIT...*
______________________________________________________________________________
String
Functions
Q4 .Write a java program to implement any five String class functions
and any five String Builder class functions.

Answer:

A) String class Functions


import java.util.*; class
Slip4
{
public static void main( String [] args)
{
Scanner s =new Scanner(System.in);
System.out.println("Enter string with speces:");
String n = s.nextLine();
System.out.println("Enter string with speces:");
String m = s.nextLine();
System.out.println("\n**Function-1 length()**\n");
System.out.println("Length of"+n+"="+n.length());
System.out.println("\n**Function-2 Compare To()**\n");

System.out.println("Enter string with speces:");

if(n.compareTo(m)==0)
System.out.println(n+"and"+m+"are equal");
else
System.out.println(n+"and"+m+"are not equal");
System.out.println("\n**Function-3 concat()**\n");
System.out.println(n.concat(m));
System.out.println(n.concat("city"));
System.out.println("\n**Function-4 IsEmpty()**\n");
System.out.println(n.isEmpty());
System.out.println("\n**Function-5 Trim()**\n");
System.out.println(n.trim().concat("Ok"));
}
}

OUTPUT:
Enter string with specs:
Faizan Mohammad
Enter string with specs:
Faizan Mohammad
**Function-1 length ()**
Length Faizan Mohammad = 17
**Function-2 Compare To ()**
Enter string with specs:
Faizan Mohammad and Faizan Mohammad are equal
**Function-3 concat ()**
Faizan Mohammad Faizan Mohammad
Faizan Mohammad city
**Function-4 IsEmpty()**
False
**Function-5 Trim ()**
Faizan Mohammad Ok
______________________________________________________________________________
B) String builder functions

import java.util.*; class


Slip0
{
public static void main( String [] args)
{
// String Builder Functions
System.out.println("\n**Function-1 append()**\n");

StringBuilder s1 = new StringBuilder("Hellow");

s1.append("Java");
System.out.println(s1);
System.out.println("\n**Function-2 insert()**\n");

s1.insert(2,"java");

System.out.println(s1);
System.out.println("\n**Function-3 replace()**\n");

s1.replace(1,3,"Java");

System.out.println(s1);
System.out.println("\n**Function-4 Delete()**\n");

s1.delete(1,3);

System.out.println(s1);
System.out.println("\n**Function-5 Reverse()**\n");
s1.reverse();
System.out.println(s1);
}
OUTPUT:
**Function-1 append ()**
HellowJava
**Function-2 insert ()**
HejavallowJava
**Function-3 replace ()**
HJavaavallowJava
**Function-4 Delete ()**
HvaavallowJava **Function-5
Reverse ()** avaJwollavaavH
Inheritance
Q5. Create a Class Company with data members name and number of
employees. Derive two classes ITCompany and Non-ITCompany.
Display the necessary details use constructor

Answer:
class Company
{
Company()
{
String name="Priya";
int no_of_emp=10;
System.out.println("Name of Employee is:"+name);
System.out.println("Numbers of employees are :"+no_of_emp);
}
}
class ITCompany extends Company
{
ITCompany()
{
String name1="Diksha";
int no_of_emp1=20;
System.out.println("Name of Employee is:"+name1);
System.out.println("Numbers of employees are :"+no_of_emp1);
}
}
class Non_ITCompany extends ITCompany
{
Non_ITCompany()
{
String name2="Yuti";
int no_of_emp2=05;
System.out.println("Name of Employee is:"+name2);
System.out.println("Numbers of employees are :"+no_of_emp2);
}
}
public class Slip5
{
public static void main(String [] args)
{
//Company obj= new Company();
//TCompany obj1= new ITCompany();
Non_ITCompany obj2= new Non_ITCompany();
}
}

OUTPUT:
Name of Employee is: Faizan
Numbers of employees are: 10
Name of Employee is: Mohammad
Numbers of employees are: 20
Name of Employee is: Gayatri
Numbers of employees are: 5
Inheritance
Q6 .Create a class School with data members name and area. Derive a class
School-one from School that displays the name and area. Derive another class
from School-two that displays the name and area.

Answer:
import java.util.*; class
School
{
Scanner sc = new Scanner(System.in);
String name;
String area;
void show()
// we could not acceses the methods and variables from superclass if we declare it as priavte.
{
System.out.println("Enter Name");
name = sc.next();
System.out.println("Enter Area");

area = sc.next();

}
}
class One extends School
{
void display()
{
System.out.println("Name of School: "+name);
System.out.println("Area of School: "+area);
}
}
class Two extends School
{
void display()
{
System.out.println("Name of School: "+name);
System.out.println("Area of School: "+area);
}
}
class Slip6
{
public static void main(String [] args)
{
One a=new One();

Two b=new Two();

a.show();//accesing method of base class


a.display();
b.show();
b.display();
}
}

OUTPUT:
Enter Name
SIBAR
Enter Area
Kondhwa, pune
Name of School: SIBAR
Area of School: Kondhwa, pune
Enter Name
VIIT Enter Area
kondhwa, pune
Name of School: VIIT
Area of School: kondhwa, pune
Interface
Q7 .Create an interface for MyPay. Initialize a variable with a
minimum amount and a member function increase () that increases
the balance by 1000. Create a class Shop that implements the above
interface.
Answer:
interface MyPay
{
int x = 10;
int increse();
}
class Shop implements MyPay
{
public int increse()
{
int cnt = 0;
cnt = x+1000;

return cnt;
}
public static void main(String [] args)
{
MyPay m = new Shop();
System.out.println("Incresed value of x is:"+m.increse());
}
}
OUTPUT:
Increased value of x is: 1010
Exception
Handling
Q8 Define a class Vote that accepts the age of a candidate. if the age
of the candidate is below 18 then throw an user defined exception
“Age not within Limit” otherwise display message “Allowed to Vote”
Answer:
import java.lang.*; import
java.io.*; import
java.util.Scanner; class Votes
extends Exception
{
public Votes (String str)
{
System.out.println(str);
}
}
class Slip8
{
public static void main(String [] args)
{
Scanner s = new Scanner(System.in);

System.out.println("Enter your age::"); int

age= s.nextInt();

try
{
if(age<18)
throw new Votes("Age not within Limit");
else
System.out.println("Your age is accepted");
}
catch(Votes v)
{
System.out.println(v);
}
}
}

OUTPUT:
Enter your age::
67
Your age is accepted
Enter your age::
16
Age not within Limit
Votes
Exception
Handling
Q9. Write a java program to show the implementation of exceptions
like
ArithmeticException, ArrayIndexOutofBoundsException,
NumberFormatException, NullPointerException and IOException.

Answer:
//implementing arithmetic Exception
public class Slip9
{
public static void main(String [] args)
{
ArrayList<String>names = new ArrayList<>

int x=5;

int y=0;
try
{
System.out.println("Division:"+(x/y));
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("Numerator is:"+x);
}
}
}
OUTPUT:
java.lang.ArithmeticException: / by zero
Numerator is:5

Implementing array index out of bound Exception.


It is the exception which occurs www try to phase array elements out of its
length

public class Slip9


{
public static void main(String [] args)
{
String [] names={"x","y","z"};
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);

System.out.println(names[3]); for(int

i=0;i<names.length;i++)

{
System.out.println(names[i]);

}
}
}

OUTPUT:
xy
z
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds
for length 3 at Slip9.main(Slip9.java:43)

implementing null pointer exception


it is nothing but an error which occurs if we tried ti perform any operation on
object which is null

public class Slip9


{
public static void main(String [] args)
{
String str = null;
System.out.println(str.length());
}
}

OUTPUT:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()"
because "<local1>" is null at Slip9.main(Slip9.java:65)

implementing Number Format Exception


when we enter non integer value then it is called as Number format Exception
import java.util.Scanner;

public class Slip9

{
public static void main(String [] args)
{
String str= null;
Scanner sc = new Scanner(System.in);

System.out.println("Enter a number:");

str= sc.next();

sc.close();

int a = Integer.parseInt(str);
System.out.println("a = "+a);
}
}

OUTPUT:
C:\Users\Faizan\Desktop\Java_Practicle>java Slip9
Enter a number:
23 a =
23
C:\Users\Faizan\Desktop\Java_Practicle>javac Slip9.java
C:\Users\Faizan\Desktop\Java_Practicle>java Slip9
Enter a number:
Faizan
Exception in thread "main" java.lang.NumberFormatException: For input string: "Faizan" at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at Slip9.main(Slip9.java:83)

implementing the IO Exception


This exception occurs whenever an input and output operation is failed or
interpreted.
For instance: If you trying to read the file that does not exist.

import java.io.*;
import java.util.*; class
Slip9
{
public static void main(String [] args) throws IOException
{
//read file using byte stream
FileInputStream f = new FileInputStream("data.txt");
int c=0;

while(c!=-1)

{
c=f.read();
System.out.print((char)c);
}
System.out.println();
//read file using character stream

FileReader fr= new FileReader("data.txt");

int i =0;

while(i!=-1) {

i=fr.read();
System.out.print((char)i);
}
fr.close();
}
}

OUTPUT:
C:\Users\Faizan\Desktop\Java_Practicle>javac Slip9.java
//When I create data.txt and run the program I got following output.
C:\Users\Faizan\Desktop\Java_Practicle>java Slip9
Welcome To SIBAR?
Welcome To SIBAR?
//I have deleted data.txt file from directory and again compile and run the programme. I got
following output
C:\Users\Faizan\Desktop\Java_Practicle>javac Slip9.java
C:\Users\Faizan\Desktop\Java_Practicle>java Slip9
Exception in thread "main" java.io.FileNotFoundException: data.txt (The system cannot find the
file specified) at java.base/java.io.FileInputStream.open0(Native Method) at
java.base/java.io.FileInputStream.open(FileInputStream.java:216) at
java.base/java.io.FileInputStream.<init>(FileInputStream.java:157) at
java.base/java.io.FileInputStream.<init>(FileInputStream.java:111) at
Slip9.main(Slip9.java:121)

Files
Q10. Write a program to accept a string as command line argument
and check whether it is a file or directory. Also perform operations as
follows: a) If it is a directory, list the names of text file. Also, display a
count showing the number of files in the directory. b) If it is a file
display various details of that file.

Answer:
import java.io.*;
class Slip10_1
{
public static void main(String a[])
{
String fname=a[0]; File
f = new File(fname); int
num=0;
if(f.isDirectory())
{
System.out.println("Given file "+fname+"is directory :");
System.out.println("List of files are : ");
String s[] = f.list(); for(int i=0; i
<s.length; i++)
{
File f1 = new File(fname,s[i]);
If(f1.isFile())
{
n++;
System.out.println(s[i]); //file name in directory
}
else
{
System.out.println(“\n”+s*i++”is a sub directory”) ;
}
System.out.println(“\n Number of files are:”+num);
}
else
{
If(f.exists())
{
System.out.println(“\n”+fname+” s a File);
System.out.println(“Details of”+fname+”are:”);
System.out.println(“path of file is”+f.getPath());
System.out.println(“Absolute path of file is”+f.getAbsolutePath());
System.out.println(“Size of file is”+f.length());
}
Else
{
System.out.println(fname+”file is not present”);
}
}
}

Files
Q11. Write a java program to merge two files in a third file. Display
the contents of all the three files .

Answer:
import java.io.*; class
slip11
{
public static void main(String[] args) throws IOException
{
// PrintWriter object for file3.txt
PrintWriter pw = new PrintWriter("file3.txt");
// BufferedReader object for file1.txt
BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
String line = br.readLine();
// loop to copy each line of
// file1.txt to file3.txt while
(line != null)
{
pw.println(line);
line = br.readLine();
}
br = new BufferedReader(new FileReader("file2.txt"));
line = br.readLine();
// loop to copy each line of
// file2.txt to file3.txt
while(line != null)
{
pw.println(line);
line = br.readLine();
}
pw.flush(); //
closing resources
br.close();
pw.close();
System.out.println("\nMerged file1.txt and file2.txt into file3.txt");
System.out.print("\nContents of File1\n:");
FileReader fr=new FileReader("file1.txt");
int i=0;
while(i!=-1)
{
i=fr.read();
System.out.print((char)i);
}
fr.close();
System.out.print("\nContents of File2\n:");
fr=new FileReader("file2.txt");
i=0;
while(i!=-1)
{
i=fr.read();
System.out.print((char)i);
}
fr.close();
System.out.print("\nContents of File3\n:");
fr=new FileReader("file3.txt");
i=0;
while(i!=-1)
{
i=fr.read();
System.out.print((char)i);
}
fr.close();
}
}

OUTPUT:
Merged file1.txt and file2.txt into file3.txt
Contents of
File1 :Faizan?
Contents of
File2 :Kasbekar?
Contents of File3
:Faizan Kasbekar
?
PS C:\Users\Faizan\Desktop\Java>

Collections
Q12 .Construct a linked list containing names of colors: red, blue,
yellow and orange. Then extend your program to do the following: i.
Display the contents of the List using an Iterator; ii. Display the
contents of the List in reverse order using a ListIterator iii. Create
another list containing pink and green. Insert the elements of this list
between blue and yellow

Answer:
import java.util.*; class
LkList
{
public static void main(String[] args)
{
LinkedList ll=new LinkedList();
ll.add("Red"); ll.add("Blue");
ll.add("Yellow");
ll.add("Orange");
Iterator i=ll.iterator();
System.out.println("\ncontents of the List using an Iterator:\n");
while(i.hasNext())
{
String s=(String)i.next();
System.out.println(s);
}
ListIterator li = ll.listIterator();
while(li.hasNext())
{
// String elt = (String)
li.next();
}
System.out.println("\ncontents of the List in reverse order using a ListIterator : ");
while(li.hasPrevious())
{
System.out.println(li.previous());
}
ll.add(2,"Pink"); //add element at second position
ll.add(3,"Green"); //add element at 3rd position
System.out.println("\nlist between blue and yellow is:");
System.out.println(ll);
}
}

OUTPUT:
/*D:\Javaprog\lab>java LkList contents
of the List using an Iterator:
Red
Blue
Yellow Orange
contents of the List in reverse order using a List Iterator :
Orange
Yellow
Blue Red
list between blue and yellow is:
[Red, Blue, Pink, Green, Yellow, Orange]
Thread
Q13. Define thread called “PrintTextThread” for printing text on
command prompt for „n‟ number of times. Create three threads and
run them. pass the text and „n‟ as parameters to the thread
constructor. Example:
a) First thread prints “I am in FY” 10 times
b) Second thread prints “I am in SY” 20 times
c) Third thread prints “I am in TY” 30 times
Answer:
import java.io.*; import
java.lang.String.*;

class Ptext extends Thread


{
String msg="";
int n;
Ptext(String msg,int n)
{
this.msg=msg;
this.n=n;
}
public void run()
{
try
{ for(int i=1;i<=n;i++)
{
System.out.println(msg+" "+i+" times");
}
System.out.println("\n ");
}
catch(Exception e){}
}
}
class Printtext
{
public static void main(String a[])
{
int n=Integer.parseInt(a[0]);
Ptext t1=new Ptext("I am in FY",n);
t1.start();
Ptext t2=new Ptext("I am in SY",n+10);
t2.start();
Ptext t3=new Ptext("I am in TY",n+20);
t3.start();
}
}
OUTPUT:
D:\Javaprog\lab>java Printtext 10
I am in FY 1 times I
am in TY 1 times
I am in SY 1 times
I am in SY 2 times
I am in SY 3 times
I am in SY 4 times
I am in SY 5 times
I am in SY 6 times I
am in TY 2 times I
am in FY 2 times
I am in FY 3 times
I am in FY 4 times
I am in FY 5 times I
am in TY 3 times I
am in SY 7 times
I am in SY 8 times
I am in SY 9 times
I am in SY 10 times
I am in SY 11 times
I am in SY 12 times
I am in SY 13 times
I am in SY 14 times
I am in SY 15 times
I am in SY 16 times
I am in SY 17 times
I am in SY 18 times
I am in SY 19 times
I am in TY 4 times I
am in FY 6 times I
am in TY 5 times
I am in SY 20 times I am in TY 6 times I am in FY 7
times I am in TY 7 times
I am in TY 8 times I
am in FY 8 times I
am in TY 9 times I
am in FY 9 times
I am in TY 10 times I
am in FY 10 times I
am in TY 11 times
I am in TY 12 times
I am in TY 13 times
I am in TY 14 times
I am in TY 15 times
I am in TY 16 times
I am in TY 17 times
I am in TY 18 times
I am in TY 19 times
I am in TY 20 times
I am in TY 21 times
I am in TY 22 times
I am in TY 23 times
I am in TY 24 times
I am in TY 25 times
I am in TY 26 times
I am in TY 27 times
I am in TY 28 times I am in TY 29 times
I am in TY 30 times
Swing
Q 14. Write a
program to
implement a
simple arithmetic
calculator. Perform
appropriate
validations.

Answer:
import java.awt.event.*; import javax.swing.*; import
java.awt.*; class calculator extends JFrame implements
ActionListener {
static JFrame f;
static JTextField l;
String s0, s1, s2;
calculator()
{
s0 = s1 = s2 = "";
}
public static void main(String args[])
{
f = new JFrame("calculator");
try {
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
calculator c = new calculator();
l = new JTextField(16);
l.setEditable(false);
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2");
b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5");
b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8");
b9 = new JButton("9"); beq1 = new JButton("="); ba = new
JButton("+"); bs = new JButton("-"); bd = new JButton("/"); bm =
new JButton("*"); beq = new JButton("C"); be = new JButton(".");
JPanel p = new JPanel(); bm.addActionListener(c);
bd.addActionListener(c); bs.addActionListener(c);
ba.addActionListener(c); b9.addActionListener(c);
b8.addActionListener(c);

b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c); //
add elements to panel
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
p.setBackground(Color.blue);
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand(); if ((s.charAt(0) >= '0' &&
s.charAt(0) <= '9') || s.charAt(0) == '.') {
if (!s1.equals(""))
s2 = s2 + s; else
s0 = s0 + s;
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
s0 = s1 = s2 = "";
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te; if
(s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
l.setText(s0 + s1 + s2 + "=" + te);
s0 = Double.toString(te);
s1 = s2 = "";
}
else {
if (s1.equals("") || s2.equals(""))
s1 = s; else
{ double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
s0 = Double.toString(te);
s1 = s;
s2 = "";
}
l.setText(s0 + s1 + s2);
}
}
}

OUTPUT:
Swing + Jdbc
Q15. Create a table Student with the fields roll number, name,
percentage Design a JFrame with the above fields and buttons for
a) insert
b) Modify
c) Delete
d) Search
e) View All
f) Exit

Answer:
JFrame File:
import java.sql.*; import javax.swing.JOptionPane;
public class student_details extends javax.swing.JFrame {
/**
* Creates new form student_details
*/
public student_details()
{ initComponents();
}
/**
* This method is called from within the constructor to initialize the form. *
WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { jLabel1 = new
javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel(); jButton1 = new
javax.swing.JButton(); jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton(); jButton4 = new
javax.swing.JButton(); jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton(); jTextField1 = new
javax.swing.JTextField(); jTextField2 = new
javax.swing.JTextField(); jTextField3 = new
javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel1.setText("Percentage: "); jLabel2.setFont(new java.awt.Font("Times
New Roman", 1, 18)); // NOI18N
jLabel2.setText("Roll no: ");
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
jLabel3.setText("Name: "); jButton1.setFont(new java.awt.Font("Times New
Roman", 1, 14)); // NOI18N
jButton1.setText("Insert"); jButton1.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton2.setText("Modify"); jButton2.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButton2ActionPerformed(evt);
}
});
jButton3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton3.setText("Search"); jButton3.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButton3ActionPerformed(evt);
}
});
jButton4.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton4.setText("Delete"); jButton4.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButton4ActionPerformed(evt);
}
});
jButton5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton5.setText("View");

jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt)
{ jButton5ActionPerformed(evt);
}
});
jButton6.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jButton6.setText("EXIT"); jButton6.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButton6ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.
Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton6)
.addComponent(jButton5))
.addGap(107, 107, 107))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(0, 30, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 282,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 74,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE,
160, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton3)
.addComponent(jButton4))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);

layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap(64, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton3)
.addComponent(jButton5)) .addPreferredGap(javax.swing.LayoutStyle.Compo
nentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton6)
.addComponent(jButton4)
.addComponent(jButton2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 25,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold> private void
jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TOO add your handling code here:
try{
Connection con; con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
String s="";
while(rs.next())
{
s=s.concat(String.valueOf(rs.getInt(1)+rs.getString(2)+rs.getFloat(3)));
}
jLabel4.setText(s);
}catch(SQLException e){System.out.println(e);}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
int x = Integer.parseInt(jTextField1.getText());
String y=jTextField2.getText(); float z =
Float.parseFloat(jTextField3.getText());
PreparedStatement p=con.prepareStatement("INSERT INTO student VAlUES (?,?,?)");
p.setInt(1, x);
p.setString(2, y);
p.setFloat(3, z);
p.executeUpdate();
JOptionPane.showMessageDialog(this, "record inserted sucessfully...");
}catch(Exception e){System.out.println(e);} // TODO add your handling code here:
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String s=JOptionPane.showInputDialog(this,"Enter roll no..");
int x=Integer.parseInt(s);
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
Statement stmt=con.createStatement();
PreparedStatement p=con.prepareStatement("delete from student where rollno=?");
p.setInt(1, x);
int r=p.executeUpdate();
if(r>=1)
JOptionPane.showMessageDialog(this, "record delete sucessfully...");
else
JOptionPane.showMessageDialog(this, "record not found...");
}catch(Exception e){System.out.println(e);}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String s=JOptionPane.showInputDialog(this,"Enter roll no.."); int
x=Integer.parseInt(s);
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student where rollno="+x);
rs.next();
System.out.println(rs.getString(2));
jTextField1.setText(String.valueOf(rs.getInt(1)));
jTextField2.setText(rs.getString(2));
jTextField3.setText(String.valueOf(rs.getFloat(3)));
}catch(Exception e){System.out.println(e);}
// TODO add your handling code here:

}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
String str = "update student set
rollno='"+jTextField1.getText()+"',name='"+jTextField2.getText()+"',percentage='"+jTextField3.g
etText()+"' where rollno='"+jTextField1.getText()+"'"; Statement
s=con.createStatement();
s.executeUpdate(str);
JOptionPane.showMessageDialog(this,"successfully updated");
}catch(Exception e){
System.out.println("The error is:"+e);
} // TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName()))
{ javax.swing.UIManager.setLookAndFeel(info.getClassName()); break;

}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(student_details.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(student_details.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(student_details.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(student_details.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() { new
student_details().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2; private
javax.swing.JButton jButton3; private
javax.swing.JButton jButton4; private
javax.swing.JButton jButton5; private
javax.swing.JButton jButton6; private
javax.swing.JLabel jLabel1; private
javax.swing.JLabel jLabel2; private
javax.swing.JLabel jLabel3; private
javax.swing.JLabel jLabel4; private
javax.swing.JTextField jTextField1; private
javax.swing.JTextField jTextField2; private
javax.swing.JTextField jTextField3;
// End of variables declaration }
Connection File:
package student;
import java.sql.*; public
class Student {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mca","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getFloat(3));
con.close();
}
}catch(SQLException e){System.out.println(e);}
}
}

OUTPUT:
JFrame:
INSERT:
AFTER INSERT:

SEARCH:
DELETE:

AFTER DELETE:
MODIFY:

AFTER MODIFY:
Swing + Jdbc
Q16.Create a table book (id, name , genre).Design a screen in swing
that accepts book id, name and genre from textfield. There are two
buttons ‘Display’ that shows the book details in jtable and Search
button that highlights the row in jtable after accepting the bookid
from a dialog box.
Answer:
package javaapplication4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.swing.*; import
java.sql.*; import
javax.swing.table.*; import
java.awt.Color;
/**
*
* @author BHAVESH
*/
public class Q16 extends javax.swing.JFrame {
/**
* Creates new form Q16
*/
public Q16()
{ initComponents();
}
/**
* This method is called from within the constructor to initialize the form. * WARNING: Do
NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { jLabel1 = new
javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel(); jTextFieldGenre = new
javax.swing.JTextField(); jTextFieldName = new
javax.swing.JTextField(); jTextFieldId = new
javax.swing.JTextField(); jButtonSearch = new
javax.swing.JButton(); jButtonDisplay = new
javax.swing.JButton(); jButtonAdd = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new
javax.swing.JTable(); jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(1450, 750));
getContentPane().setLayout(null); jLabel1.setFont(new
java.awt.Font("Verdana", 1, 18)); // NOI18N
jLabel1.setText("Genre :");
getContentPane().add(jLabel1); jLabel1.setBounds(30, 250,
150, 24); jLabel2.setFont(new java.awt.Font("Verdana", 1,
36)); // NOI18N jLabel2.setText("BOOK");
getContentPane().add(jLabel2); jLabel2.setBounds(400, 20, 140,
50); jLabel3.setFont(new java.awt.Font("Verdana", 1, 18)); //
NOI18N jLabel3.setText("Book Name :");
getContentPane().add(jLabel3); jLabel3.setBounds(30, 180, 150,
24); jTextFieldGenre.setFont(new java.awt.Font("Verdana", 1,
14)); // NOI18N getContentPane().add(jTextFieldGenre);
jTextFieldGenre.setBounds(220, 250, 160, 30);
jTextFieldName.setFont(new java.awt.Font("Verdana", 1, 14)); //
NOI18N getContentPane().add(jTextFieldName);
jTextFieldName.setBounds(220, 180, 160, 30);
jTextFieldId.setFont(new java.awt.Font("Verdana", 1, 14)); //
NOI18N getContentPane().add(jTextFieldId);
jTextFieldId.setBounds(220, 120, 160, 30);
jButtonSearch.setFont(new java.awt.Font("Verdana", 1, 24)); //
NOI18N jButtonSearch.setText("SEARCH");
jButtonSearch.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButtonSearchActionPerformed(evt);
}
});
getContentPane().add(jButtonSearch);
jButtonSearch.setBounds(730, 320, 180, 70);
jButtonDisplay.setFont(new java.awt.Font("Verdana", 1, 24)); // NOI18N
jButtonDisplay.setText("DISPLAY"); jButtonDisplay.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButtonDisplayActionPerformed(evt);
}
});
getContentPane().add(jButtonDisplay);
jButtonDisplay.setBounds(470, 320, 180, 70); jButtonAdd.setFont(new
java.awt.Font("Verdana", 1, 24)); // NOI18N jButtonAdd.setText("ADD
BOOK"); jButtonAdd.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(java.awt.event.ActionEvent evt)
{ jButtonAddActionPerformed(evt);
}
});
getContentPane().add(jButtonAdd);
jButtonAdd.setBounds(110, 320, 180, 70);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Book ID", "Book Name", "Genre"
}
));
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1); jScrollPane1.setBounds(450,
120, 520, 190); jLabel4.setFont(new java.awt.Font("Verdana", 1,
18)); // NOI18N

jLabel4.setText("Book ID :");
getContentPane().add(jLabel4);
jLabel4.setBounds(30, 120, 150, 24);
pack();
}// </editor-fold> private void
jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Connection con=DriverManager.getConnection("jdbc:mysql:///Q16","root","");
int x=Integer.parseInt(jTextFieldId.getText());
String y=jTextFieldName.getText();
String z=jTextFieldGenre.getText();
PreparedStatement p=con.prepareStatement("Insert into Book values(?, ?, ?)");
p.setInt(1,x);
p.setString(2, y);
p.setString(3, z);
p.executeUpdate();
JOptionPane.showMessageDialog(this,"Record Inserted Successfully......");
}
catch(Exception e)
{
System.out.println(e);
}
}
private void jButtonDisplayActionPerformed(java.awt.event.ActionEvent evt) {
try
{
//Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql:///Q16","root","");
Statement s =con.createStatement();
String sql="select * from book";
ResultSet rs=s.executeQuery(sql);
while(rs.next())
{
String ID=String.valueOf(rs.getInt("Book_Id"));
String Name=rs.getString("Book_Name");
String Genre=rs.getString("Genre");
String tbData[]={ID,Name,Genre};
DefaultTableModel tblModel=(DefaultTableModel)jTable1.getModel();
tblModel.addRow(tbData);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {
Function f=new Function(); ResultSet rs=null;
rs=f.find(JOptionPane.showInputDialog(this, "Enter Book ID : "));
//rs=f.find(jTextFieldSearch.getText());
try
{ if(rs.
next())
{
//jTextFieldD.setText(rs.getString("Source"));
JOptionPane.showMessageDialog(null, "Data Found");
}
else
{
JOptionPane.showMessageDialog(null, "Data Not Found");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
/* try
{
Connection con = DriverManager.getConnection("jdbc:mysql:///Q16","root","");
Statement s =con.createStatement();
String a=JOptionPane.showInputDialog(this, "Enter Book ID : ");
String sql="select * from book";
ResultSet rs=s.executeQuery(sql);
while(rs.next())
{
String ID=String.valueOf(rs.getInt("Book_Id"));
String Name=rs.getString("Book_Name");
String Genre=rs.getString("Genre");
String tbData[]={ID,Name,Genre};
DefaultTableModel tblModel=(DefaultTableModel)jTable1.getModel();
tblModel.addRow(tbData);
}
jTable1.addRowSelectionInterval(3,3);
jTable1.setForeground(Color.BLUE);
}
catch(Exception e)
{
//JOptionPane.showMessageDialog(null, e.getMessage());
}*/
}
public class Function
{
Connection con=null;
ResultSet rs=null;
PreparedStatement ps=null;
public ResultSet find(String s)
{
try
{
con = DriverManager.getConnection("jdbc:mysql:///Q16","root","");
ps=con.prepareStatement("select * from book where Book_Id = ?");
ps.setString(1,s);
rs=ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName()))
{ javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Q16.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (InstantiationException ex)
{ java.util.logging.Logger.getLogger(Q16.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Q16.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Q16.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{ new
Q16().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonDisplay;
private javax.swing.JButton jButtonSearch;
private javax.swing.JLabel jLabel1; private
javax.swing.JLabel jLabel2; private
javax.swing.JLabel jLabel3; private
javax.swing.JLabel jLabel4; private
javax.swing.JScrollPane jScrollPane1; private
javax.swing.JTable jTable1; private
javax.swing.JTextField jTextFieldGenre; private
javax.swing.JTextField jTextFieldId; private
javax.swing.JTextField jTextFieldName;
// End of variables declaration
}
OUTPUT:
Applet
Q17. Create an Applet which displays a message in the center of the
screen. The message indicates the events taking place on the applet
window. Handle events like mouse click, mouse moves, mouse
dragged, mouse pressed. The message should update each time an
event occurs. The message should give details of the event such as
which mouse button was pressed (Hint: Use repaint (), MouseListener,
MouseMotionListener)

Answer:
Q17.html
<html>
<body>
<applet code="Q17.java" width="400" height="200">
</applet>
</body>
</html>

Q 17.java import
java.awt.*; import
java.applet.*; import
java.awt.event.*;
/*
<applet code="Q17.class" width=400 height=200>
</applet> */
public class Q17 extends Applet implements MouseMotionListener,MouseListener,KeyListener
{
String msg="";
public void init()
{
setBackground(Color.cyan);
addMouseMotionListener(this);
addMouseListener(this); addKeyListener(this);
}
public void paint(Graphics g)
{
g.drawString(msg,10,10);
}
public void mouseDragged(MouseEvent e)
{
msg="Mouse Dragged.";
repaint();
}
public void mouseMoved(MouseEvent e)
{
msg="Mouse Moved.";
repaint();
}
public void mouseClicked(MouseEvent e)
{
msg="Mouse Button "+e.getButton()+"clicked.";
repaint();
}
public void mousePressed(MouseEvent e)
{
msg="Mouse Button "+e.getButton()+"pressed.";
repaint();
}
public void mouseReleased(MouseEvent e)
{
msg="Mouse Button Released.";
repaint();
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void keyTyped(KeyEvent e)
{
msg="Key Typed "+ e.getKeyChar();
repaint();
}
public void keyPressed(KeyEvent e)
{
msg="Key pressed "+ e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e)
{
}
}

Output:
Servlet
Handling
Q18. Design a servlet which counts how many times a user has visited
a web page. If the user is visiting the page for the first time then
display a message “Welcome”. If the user is revisiting the page, then
display the number of times page is visited (Use Cookies)
Answer:
Web.xml file(servlet entry)
<?xml version = “1.0” encoding=”ISO-8859-1”?>
<web-app>
<servlet>
<servlet-name>VisitServlet</servlet-name>
<servlet-class>VisitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VisitServlet</servlet-name>
<url-pattern>/servlet/VisitServlet</url-pattern></servlet-mapping></web-app>

Java:
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*; public class
VisitServlet extends HttpServlet
{
static int i=1;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String k=String.valueOf(i); Cookie
c = new Cookie("visit",k);
response.addCookie(c); int
j=Integer.parseInt(c.getValue());
if(j==1)
{
out.println("Welcome");
}
else { out.println("You visited "+i+" times");
}
i++;
}
}

JSP
Q19. Create a JSP page which accepts user name in a text box and
greet the user according to the time on server side. Example: Input :
User
Name ABC Output : Good Morning ABC/Good Afternoon ABC/ Good
Evening ABC
Answer:
HTML:

<html>
<body>
<form action = “Slip22.jsp”method=”post”>
Enter your name:<input type =”text” name =”name”><br>
<input type = “submit” value = “submit”>
</form>
</body>
</html>

<%@page import="java.util.Calendar"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
Calendar rightnow = Calendar.getInstance(); int
time = rightnow.get(Calendar.HOUR_OF_DAY);
if(time > 0 && time <= 12)
{
out.println("Good Morning"+name);
}
else if(time < 12 && time >=16)
{
out.println("Good Afternoon"+name);
}
Else
{
out.println("Good Night"+name);
}
%>
JSP
Q20. Create a JSP page for an online multiple choice test. The
questions are randomly selected from a database and displayed on
the screen. The choices are displayed using radio buttons. When the
user clicks on next, the next question is displayed. When the user
clicks on submit, display the total score on the screen.

Answer:
<%@page import="java.sql.*,java.util.*"%>
<%
Class.forName("org.postgresql.Driver");
Connection con =
DriverManager.getConnection( "jdbc:postgresql:t
y1","postgres",""); Set s = new TreeSet();
while(true)
{
int n = (int)(Math.random()*11+1);
s.add(n); if(s.size()==5)
break;
}
PreparedStatement ps = con.prepareStatement("select * from questions where
qid=?");
%>
<form method='post' action='accept_ans.jsp'>
<table width='70%' align='center'>
<%
int i=0;
Vector v = new Vector(s);
session.setAttribute("qids",v); int qid =
Integer.parseInt(v.get(i).toString());
ps.setInt(1,qid);
ResultSet rs = ps.executeQuery();
rs.next(); %>
<tr>
<td><b>Question:<%=i+1%></b></td>
</tr>
<tr>
<td><pre><b><%=rs.getString(2)%></pre></b></td>
</tr>
<tr>
<td>
<b>
<input type='radio’ name=’op’ value=1><%=rs.getString(3)%<br> <input
type='radio’ name=’op’ value=2><%=rs.getString(4)%<br> <input
type='radio’ name=’op’ value=3><%=rs.getString(5)%<br>
<input type='radio’ name=’op’ value=4><%=rs.getString(6)%<br><br>
</b>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Next' name='ok'>
<input type='submit' value='Submit' name='ok'>
</td>
</tr>
</table>
<input type='hidden' name='qno' value=<%=qid%>>
<input type='hidden' name='qid' value=<%=i+1%>>
</form>
</body>

acceptans.jsp:
%@page import="java.sql.*,java.util.*"%
<%
Class.forName("org.postgresql.Driver");
Connection con =
DriverManager.getConnection( "jdbc:postgresql:ty1","postgres","");
Vector answers = (Vector)session.getAttribute("answers");
if(answers==null) answers = new Vector();
int qno = Integer.parseInt(request.getParameter("qno"));
int ans = Integer.parseInt(request.getParameter("op")); int
i = Integer.parseInt(request.getParameter("qid"));
answers.add(qno+" "+ans);

session.setAttribute("answers",answers); String
ok = request.getParameter("ok");
if(ok.equals("Submit") || i==5)
{
response.sendRedirect("result.jsp"); return;
}
PreparedStatement ps = con.prepareStatement("select * from questions where
qid=?");
%>
<form method='post' action='accept_ans.jsp'>
<table width='70%' align='center'>
<%
Vector v = (Vector)session.getAttribute("qids"); int
qid = Integer.parseInt(v.get(i).toString());
ps.setInt(1,qid);
ResultSet rs = ps.executeQuery(); rs.next();
%>
<tr>
<td><b>Question:<%=i+1%></b></td>
</tr>
<tr>
<td><pre><b><%=rs.getString(2)%></pre></b></td>
</tr>
<tr>
<td>
<b>
<input type='radio' name='op' value=1><%=rs.getString(3)%><br>
<input type='radio' name='op' value=2><%=rs.getString(4)%><br>
<input type='radio' name='op' value=3><%=rs.getString(5)%><br>
<input type='radio' name='op' value=4><%=rs.getString(6)%><br><br>
</b>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Next' name='ok'>
<input type='submit' value='Submit' name='ok'>
</td>
</tr>
</table>
<input type='hidden' name='qno' value=<%=qid%>>
<input type='hidden' name='qid' value=<%=i+1%>>
</form>
</body>
result.jsp:
<%@page import="java.sql.*,java.util.*,java.text.*"%>
<%
Class.forName("org.postgresql.Driver");
Connection con =
DriverManager.getConnection( "jdbc:postgresql:ty1","postgres","");
Vector v = (Vector)session.getAttribute("answers"); if(v==null)
{
%>
<h1>No questions answered</h1>
<% return;
}
PreparedStatement ps = con.prepareStatement("select ans from questions
where qid=?"); int tot=0;
for(int i=0;i<v.size();i++)
{
String str = v.get(i).toString(); int
j = str.indexOf(' ');
int qno = Integer.parseInt(str.substring(0,j)); int
gans = Integer.parseInt(str.substring(j+1));
ps.setInt(1,qno);
ResultSet rs = ps.executeQuery();
rs.next(); int cans = rs.getInt(1);
if(gans==cans) tot++;
}
session.removeAttribute("qids"); session.removeAttribute("answers");
session.removeAttribute("qid");
%>
<h3>Score:<%=tot%></h1>
<center><a href='exam.jsp'>Restart</a></center>
</body>

___________________________________________________________________

You might also like