System.out.println

advertisement
JAVA-B&C
Practical No. 1
Aim : Write a program to demonstrate command line parameter.
public class Switch
{
public static void main(String key[])
{
int x=Integer.parseInt(key[0]);
switch(x){
case 1: System.out.println(“Monday”);
break;
case 2: System.out.println(“Tuesday”);
break;
case 3: System.out.println(“Wednesday”);
break;
case 4: System.out.println(“Thursday”);
break;
case 5: System.out.println(“Friday”);
break;
case 6: System.out.println(“Saturday”);
break;
case 7: System.out.println(“Sunday”);
break;
default :System.out.println(“Invalid Number of Day”);
}
}
}
Practical No. 2
Aim: Write a program to implement method overloading.
class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
}
class Overload
{
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output :
Practical No. 3
Aim : Write a program to use wrapper class.
class WrapperDemo
{
public static void main (String args[])
{
Integer intObj1 = new Integer (25);
Integer intObj2 = new Integer (“25″);
Integer intObj3= new Integer (35);
//compareTo demo
System.out.println(“Comparing using compareTo Obj1 and Obj2: ” +
intObj1.compareTo(intObj2));
System.out.println(“Comparing using compareTo Obj1 and Obj3: ” +
intObj1.compareTo(intObj3));
//Equals demo
System.out.println(“Comparing using equals Obj1 and Obj2: ” + intObj1.equals(intObj2));
System.out.println(“Comparing using equals Obj1 and Obj3: ” + intObj1.equals(intObj3));
Float f1 = new Float(“2.25f”);
Float f2 = new Float(“20.43f”);
Float f3 = new Float(2.25f);
System.out.println(“Comparing using compare f1 and f2: ” +Float.compare(f1,f2));
System.out.println(“Comparing using compare f1 and f3: ” +Float.compare(f1,f3));
//Addition of Integer with Float
Float f = intObj1.floatValue() + f1;
System.out.println(“Addition of intObj1 and f1: “+ intObj1 +”+” +f1+”=” +f );
}
}
Output :
Practical No. 4
Aim: Write a program to implement static methods to find the square of number and
power function.
class ImpPower
{
static long Ipower(int num,int pow)
{
if(pow==0)
{
return 1;
}
else if(pow==1)
{
return num;
}
else
{
int m=num;
for(int i=1;i<=pow;i++)
{
num=num*m;
}
return num;
}
}
}
class Fourth
{
public static void main(String args[])
{
int m=3,p=4;
System.out.println(“3 raise to power 4 is : “+ImpPower.Ipower(m, p));
}
}
Output :
Practical No. 5
Aim : Write a program to sort an array using bubble sort method.
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
System.out.println(“Input number of integers to sort”);
n = in.nextInt();
int array[] = new int[n];
System.out.println(“Enter ” + n + ” integers”);
for (c = 0; c < n; c++)
array[c] = in.nextInt();
for (c = 0; c < ( n – 1 ); c++) {
for (d = 0; d < n – c – 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap
= array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
System.out.println(“Sorted list of numbers”);
for (c = 0; c < n; c++)
System.out.println(array[c]);
}
}
Output :
Practical No. 6
Aim : Write a program to compare two objects using object as a parameter
class BillingAddress
{
private String firstName;
private String lastName;
public BillingAddress(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public boolean equals(Object obj)
{
boolean isEqual = false;
if (this.getClass() == obj.getClass())
{
BillingAddress billingAddress = (BillingAddress) obj;
if ((billingAddress.firstName).equals(this.firstName) &&
(billingAddress.lastName).equals(this.lastName))
{
isEqual = true;
}
}
return isEqual;
}
}
class Sixth
{
public static void main(String[] arg)
{
BillingAddress obj1 = new BillingAddress(“john”, “bates”);
BillingAddress obj2 = new BillingAddress(“Abc”, “Kumar”);
if (obj1.equals(obj2))
{
System.out.println(“Both the objects are equal”);
}
else
{
System.out.println(“Both the objects are not equal”);
}
} }
Output :
Practical No. 7
Aim: Write a program to find the area of rectangle; circle and triangle using an
abstract class (implement dynamic dispatch).
import java.util.Scanner;
abstract class A
{
abstract void area();
}
class Rectangle extends A
{
void area()
{
Scanner scan= new Scanner(System.in);
System.out.println(“Enter the lenght : “);
int Len=scan.nextInt();
System.out.println(“Enter the Breadth : “);
int bre=scan.nextInt();
System.out.println(“Enter the Height : “);
int high=scan.nextInt();
int a=Len*bre*high;
System.out.println(“Area of Rectangle : “+a);
}
}
class Triangle extends A
{
void area()
{
Scanner scan= new Scanner(System.in);
System.out.println(“Enter the Base : “);
int Base=scan.nextInt();
System.out.println(“Enter the Height : “);
int height=scan.nextInt();
double a=0.5*Base*height;
System.out.println(“Area of Triangle : “+a);
}
}
class Circle extends A
{
void area()
{
Scanner scan= new Scanner(System.in);
System.out.println(“Enter the Radius : “);
int rad=scan.nextInt();
double a=3.14*rad*rad;
System.out.println(“Area of Circle : “+a);
}
}
public class Dispatch
{
public static void main(String args[])
{
Rectangle b = new Rectangle();
Triangle c = new Triangle();
Circle d= new Circle();
A r;
r = b;
r.area();
r = c;
r.area();
r = d;
r.area();
}
}
Output :
Practical No. 8
Aim: Write a program to demonstrate single inheritance.
(Create a class box with data member width, height, depth & member function volume
to calculate volume of box with all the necessary constructor, derive a new class
boxweight with data member weight which constructor & method to display with
height & weight)
class Box
{
int width;
int height;
int depth;
Box(int w, int h,int d)
{
width=w;
height=h;
depth=d;
}
int volume()
{
return width*height*depth;
}
}
class boxweight extends Box
{
int weight;
boxweight(int w,int h,int d,int weigh)
{
super(w,h,d);
weight=weigh;
}
void display()
{
System.out.println(“Width : “+width);
System.out.println(“Height : “+height);
System.out.println(“Depth : “+depth);
System.out.println(“Weight : “+weight);
System.out.println(“Volume : “+volume());
}
}
class eight
{
public static void main(String args[])
{
boxweight b= new boxweight(4,5,6,7);
b.display();
}
Output :
}
Practical No. 9
Aim :Write a program to demonstrate multiple inheritance using interface
(Create a class student with data member roll no & mark1,mark2,mark3 & create a
interface sportswt with data member wt, create another class result derive from
student & sportwt with member function to calculate total & to implement method of
interface)
class Student
{
int rollNumber;
float marks1,marks2,marks3;
void getdata(int r,float m1,float m2,float m3)
{
rollNumber=r;
marks1=m1;
marks2=m2;
marks3=m3;
}
void putdata()
{
System.out.println(“Roll NUmber : “+rollNumber);
System.out.println(“Marks1 : “+marks1);
System.out.println(“Marks2 : “+marks2);
System.out.println(“Marks3 : “+marks3);
}
}
interface Sports
{
float wt=6.0F;
void putwt();
}
class Results extends Student implements Sports
{
float total;
public void putwt()
{
System.out.println(“Sports wt : “+wt);
}
void display()
{
total= marks1+marks2+marks3+wt;
putdata();
putwt();
System.out.println(“Total score : “+ total);
}
}
class ninth
{
public static void main(String args[])
{
Results student1= new Results();
student1.getdata(4,50,60,70);
student1.display();
}
}
Output :
Practical No. 10
Aim : Write a program to demonstrate package and access modifier.
(create class protection with 3 data member of public, private, protected type. Create
another class derive which is derived from protection & try to display all the member of
protection class. Create another class in same package to use object of protection &
display all the members of protection.)
SamplePackage:-
package packdemo;
public class samepackage
{
public void show1()
{
protection p=new protection(3,8,9);
System.out.println(“m= “+p.m);
//System.out.println(“n= “+p.n);
System.out.println(“o= “+p.o);
}
}
Derived Package:-
package packdemo;
public class derived extends protection
{
public derived(int m1,int n1,int o1)
{
super(m1,n1,o1);
}
public void show()
{
System.out.println(“m= “+m);
//System.out.println(“n= “+n);
System.out.println(“o= “+o);
}
}
Protection package:-
Packdemo:-
import packdemo.protection;
import packdemo.derived;
import packdemo.samepackage;
class packdemomain
{
public static void main(String[] args)
{
derived d=new derived(2,4,6);
d.show();
samepackage s=new samepackage();
s.show1();
}
}
Output :
Practical No. 11
Aim: Write a program that will read a text and count all the occurrences of particular
word.
import java.util.*;
class TextSearch
{
public static void main(String as[]) throws Exception
{
Scanner scan=new Scanner(System.in);
int i=0,count=0;
String text=””,s=””;
System.out.println(“Enter Text:(press ENTER to stop)\n”);
s=scan.nextLine();
while(s.length()!=0)
{
text+=s;
s=scan.nextLine();
}
System.out.println(“Enter search word:”);
s=scan.nextLine();
while(true)
{
i=text.indexOf(s,i);
if(i==-1)
break;
System.out.println(“Word found at position:”+(i+1));
count++;
i+=s.length();
}
System.out.println(“Number of occurrences of given word:”+count);
}
}
Output :
Practical No. 12
Aim : Write a program that will read a string and rewrite it in alphabetical order
(STRING AS GINRST).
import java.util.*;
class twelve
{
public static void main(String args[])throws Exception
{
Scanner scan = new Scanner(System.in);
System.out.println(“Enter a string:”);
String s = scan.nextLine();
char input[] = s.toCharArray();
for(int i = input.length-2; i>=0; i–)
{
for(int j=0; j<=i; j++)
{
if(input[j] > input[j+1])
{
char temp = input[j];
input[j] = input[j+1];
input[j+1] = temp;
}
}
}
System.out.println(“In sorted Order: ” + new String(input));}}
Output :
Practical No. 13
Aim Write a program to count the number of vowel and consonant in the given string
import java.io.Console;
public class Vowels {
public static final char[] CONSONANTS = {
‘b’, ‘c’, ‘d’, ‘f’, ‘g’, ‘h’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’};
public static final char SPACE = ‘ ‘;
static char[] getConsonants() {
return CONSONANTS;
}
static boolean isConsonant(char c) {
boolean isConsonant = false;
for (int i = 0; i < getConsonants().length; i++) {
if (getConsonants()[i] == c) {
isConsonant = true;
break;
}
}
return isConsonant;
}
static boolean isSpace(char c) {
return SPACE == c;
}
public static void main(String[] args) {
int spaces
= 0;
int consonants = 0;
int vowelcount = 0;
Console console = System.console();
console.format(“Enter a String:”);
String text = console.readLine();;
for (int index = 0; index < text.length(); index++) {
char letter = text.charAt(index);
if (!isSpace(letter)) {
if (isConsonant(letter)) {
consonants++;
} else {
vowelcount++;
}
} else {
spaces++;
}
}
System.out.println (“Vowels:” + vowelcount + “\nConsonants :” + consonants + “\nSpaces :
” + spaces);
}
}
Output :
Practical No. 14
Aim: Write a program to check where given string is palindrome or not.
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse=””;
Scanner in = new Scanner(System.in);
System.out.println(“Enter a string to check if it is a palindrome”);
original = in.nextLine();
int length = original.length();
for ( int i = length – 1 ; i >= 0 ; i– )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println(“Entered string is a palindrome.”);
else
System.out.println(“Entered string is not a palindrome.”);
}
}
Output :
Practical No. 15
Aim: Write a program to demonstrate multiple catch statement.
class Error4
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}
int y=a[1]/a[0];
System.out.println(“y = “+y);
}
}
Output :
Practical No. 16
Aim: Write a program to create own exception and Create a student class if marks is
greater than 100 to use this exception.
import java.lang.Exception;
import java.util.*;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class Student
{
public static void main(String args[])
{
Scanner scan= new Scanner(System.in);
System.out.println(“Enter the marks : “);
int mrks1=scan.nextInt();
try
{
if(mrks1>100)
{
throw new MyException(“Marks are out of Bound”);
}
}
catch(MyException e)
{
System.out.println(“Caught my exception : “);
System.out.println(e.getMessage());
}
finally
{
System.out.println(“I am always here”);
}
}
}
Output :
Practical No. 17
Aim: Write a program to implement multithreading for multiplication table, Prime
Number and Fibonacci Series.
class tm extends Thread
{
public void run()
{
System.out.println(“This is a multiplication table.”);
}
}
class tp extends Thread
{
public void run()
{
int count=0;
System.out.println(“Prime Numbers : “);
for(int i=2;i<30;i++)
{
count=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==0)
{
System.out.print(i+”\t”);
}
}
System.out.println();
}
}
class tf extends Thread
{
public void run()
{
int a=-1,b=1,c=0;
System.out.println(“Fibonacci Series.”);
for( c=0;c<=21;c++)
{
c=a+b;
System.out.print(c+”\t”);
a=b;
b=c;
}
System.out.println();
}
}
class Threading
{
public static void main(String args[])
{
tf tf1=new tf();
tp tp1=new tp();
tm tm1= new tm();
//tf1.setPriority(Thread.MAX_PRIORITY);
tf1.start();
tp1.start();
tm1.start();
}
}
Output :
Practical No. 18
Aim: Write a program to Demonstrate Thread Priority
class thrun implements Runnable
{
Thread t;
boolean runn = true;
thrun(String st,int p)
{
t = new Thread(this,st);
t.setPriority(p);
t.start();
}
publicvoid run()
{
System.out.println(“Thread name : ” + t.getName());
System.out.println(“Thread Priority : ” + t.getPriority());
}
}
class priority
{
publicstaticvoid main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
thrun t1 = new thrun(“Thread1″,Thread.NORM_PRIORITY + 2);
thrun t2 = new thrun(“Thread2″,Thread.NORM_PRIORITY – 2);
System.out.println(“Main Thread : ” + Thread.currentThread());
System.out.println(“Main Thread Priority : ” + Thread.currentThread().getPriority());
}
}
Output :
Main Thread : Thread[main,10,main]
Main Thread Priority : 10
Thread name : Thread2
Thread name : Thread1
Thread Priority : 7
Thread Priority : 3
Practical No. 19
Aim : Write an applet program to draw shape like Indian flag, Ashok chakra.
import java.awt.*;
import java.applet.*;
import javax.swing.*;
/*<applet code=”lifecycleApplet” width=300 height=200>
</applet>*/
public class lifecycleApplet extends JApplet
{
public void init()
{
System.out.println(“This is init”);
}
public void start()
{
System.out.println(“Applet started”);
}
public void paint(Graphics g)
{
g.drawString(“Vande Mathram”,20,30);
g.drawRect(166,49,336,79);
g.setColor(Color.orange);
for(int i=0;i<20;i++)
{
g.drawLine(166,48+i,500,48+i);
}
g.setColor(Color.blue);
g.drawOval(310,70,30,30);
g.fillOval(310,70,30,30);
g.setColor(Color.black);
g.drawLine(166,68,500,68);
g.drawLine(166,100,500,100);
g.setColor(Color.green);
for(int i=0;i<20;i++)
{
g.drawLine(166,105+i,500,105+i);
}
g.setColor(Color.black);
g.drawLine(166,49,166,549);
g.drawRect(136,549,166,589);
//System.out.println(“Applet just painted”);
}
public void stop()
{
System.out.println(“Applet stoped”);
}
public void destroy()
{
System.out.println(“Applet destroyed”);
}
}
Practical No. 20
Aim: Write an applet program to perform addition, subtraction, multiplication and
division of two numbers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=calculator height=400 width=600></applet>*/
public class calculator extends JApplet implements ActionListener
{
private JLabel l1,l2,l3;
private JTextField t1,t2,t3;
private JButton b1,b2,b3,b4;
public void init()
{
Container c=getContentPane();
c.setLayout(new GridLayout(5,2));
l1=new JLabel(“First No. :”);
l2=new JLabel(“Second No. :”);
l3=new JLabel(“Result :”);
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
b1=new JButton(“Add”);
b2=new JButton(“Sub”);
b3=new JButton(“Mul”);
b4=new JButton(“Div”);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
c.add(l1);
c.add(t1);
c.add(l2);
c.add(t2);
c.add(l3);
c.add(t3);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
}
public void actionPerformed(ActionEvent ae)
{
int a,b,c;
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
if(ae.getSource()==b1)
{
c=a+b;
t3.setText(“”+c);
}
if(ae.getSource()==b2)
{
c=a-b;
t3.setText(“”+c);
}
if(ae.getSource()==b3)
{
c=a*b;
t3.setText(“”+c);
}
if(ae.getSource()==b4)
{
c=a/b;
t3.setText(“”+c);
}
}
}
Practical No. 21
Aim : Write program using swing to create scientific calculator.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Calculator extends JFrame {
private final Font BIGGER_FONT = new Font(“monspaced”,Font.PLAIN, 20);
private JTextField textfield;
private boolean number = true;
private String equalOp = “=”;
private CalculatorOp op = new CalculatorOp();
public Calculator() {
textfield = new JTextField(“”, 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);
ActionListener numberListener = new NumberListener();
String buttonOrder = “1234567890 “;
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(” “)) {
buttonPanel.add(new JLabel(“”));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {“+”, “-”, “*”, “/”,”=”,”C”,”sin”,”cos”,”log”};
for (int i = 0; i < opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST);
this.setContentPane(pan);
this.pack();
this.setTitle(“Calculator”);
this.setResizable(false);
}
private void action() {
number = true;
textfield.setText(“”);
equalOp = “=”;
op.setTotal(“”);
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String displayText = textfield.getText();
if (e.getActionCommand().equals(“sin”))
{
textfield.setText(“” + Math.sin(Double.valueOf(displayText).doubleValue()));
}else
if (e.getActionCommand().equals(“cos”))
{
textfield.setText(“” + Math.cos(Double.valueOf(displayText).doubleValue()));
}
else
if (e.getActionCommand().equals(“log”))
{
textfield.setText(“” + Math.log(Double.valueOf(displayText).doubleValue()));
}
else if (e.getActionCommand().equals(“C”))
{
textfield.setText(“”);
}
else
{
if (number)
{
action();
textfield.setText(“”);
}
else
{
number = true;
if (equalOp.equals(“=”))
{
op.setTotal(displayText);
}else
if (equalOp.equals(“+”))
{
op.add(displayText);
}
else if (equalOp.equals(“-”))
{
op.subtract(displayText);
}
else if (equalOp.equals(“*”))
{
op.multiply(displayText);
}
else if (equalOp.equals(“/”))
{
op.divide(displayText);
}
textfield.setText(“” + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
}
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp {
private int total;
public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return “”+total;
}
public void setTotal(String n) {
total = convertToNumber(n);
}
public void add(String n) {
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}
public void divide(String n) {
total /= convertToNumber(n);
}
private int convertToNumber(String n) {
return Integer.parseInt(n);
}
}
}
class SwingCalculator {
public static void main(String[] args) {
JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Practical No. 22
Aim : Create an applet program for Banner; banner text (Your Roll No.) should
be passed as parameter. This applet creates a thread that scrolls the message contained
in message right to left across the applet’s window & also uses status.
import java.awt.*;
import javax.swing.*;
import java.util.*;
/*
<applet code=Bannerdemo width=400 height=400>
<param name=rno value=’MCA17′>
</applet>
*/
public class Bannerdemo extends JApplet implements Runnable
{
Thread t;
String s,tmp,rno;
int i;
public Bannerdemo()
{
tmp=” “;
i=0;
s=” “;
//rno=getParameter(“rno”);
}
public void init()
{
tmp=” “;
i=0;
s=” “;
rno=getParameter(“rno”);
//rno=new String(“MCA17″);
}
public void run()
{
for(;;)
{
try{
if(i==100)
i=0;
repaint();
Thread.sleep(250);
tmp=tmp+” “;
s=tmp;
i=i+2;
rno=rno.substring(1,rno.length()).concat(rno.substring(0,1));
}catch(Exception e) {}
}
}
public void start()
{
t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
setBackground(new Color(255,255,255-(i+i)));
g.clearRect(0,0,1000,1000);
g.drawString(“MCA17″+s,300-i,10);
g.drawString(rno,300-i,50);
}
}
Practical No. 23
Aim: Write a program using swing to create a registration form.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class biodata extends JFrame implements ActionListener {
JLabel l1,l2,l3,l4,l5,l6,l7;
JTextField t1,t2;
JTextArea ta1;
JCheckBox c1,c2,c3;
JTable tb1;
JButton b1,b2;
JRadioButton r1,r2;
JScrollPane sp1,sp2;
JComboBox cb1,cb2,cb3;
int i;
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
Container con;
public biodata(){
l1=new JLabel(“Name :-”);
l2=new JLabel(“Address :-”);
l3=new JLabel(“Telephone No. :-”);
l4=new JLabel(“Gender :-”);
l5=new JLabel(“Date Of Birth :-”);
l6=new JLabel(“Language known :-”);
l7=new JLabel(“Education Qualification :-”);
t1=new JTextField(20);
t2=new JTextField(20);
ta1=new JTextArea(30,20);
//JRadioButton
r1=new JRadioButton(“Male”);
r2=new JRadioButton(“Female”);
//JCheckBox
c1=new JCheckBox(“English”);
c2=new JCheckBox(“Marathi”);
c3=new JCheckBox(“Hindi”);
//JComboBox
cb1=new JComboBox();
for(int i=1;i<=31;i++){
cb1.addItem(“”+i);}
cb2=new JComboBox();
for(int i=1;i<=12;i++){
cb2.addItem(“”+i);}
cb3=new JComboBox();
for(int i=1990;i<=2020;i++){
cb3.addItem(“”+i);}
b1=new JButton(“ok”);
b1.addActionListener(this);
b2=new JButton(“Cancel”);
b2.addActionListener(this);
sp1=new
JScrollPane(ta1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZON
TAL_SCROLLBAR_ALWAYS);
tb1=new JTable();
Object
rowdata[][]={{“S.S.C.”,”2008″,”70%”,”I”},{“H.S.C”,”2010″,”64%”,”I”},{“B.S.C(cs)”,”201
3″,”80%”,”I”}};
Object Coldata[]={“Board”,”Year of Passing”,”Percentage”,”Class”};
tb1=new JTable(rowdata,Coldata);
sp2=new
JScrollPane(tb1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZON
TAL_SCROLLBAR_ALWAYS);
ButtonGroup gp=new ButtonGroup();
gp.add(r1);gp.add(r2);
con=getContentPane();
con.setLayout(gbl);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.weightx=1.0;gbc.weighty=1.0;
//name
gbc.gridx=0;gbc.gridy=0;
con.add(l1,gbc);
gbc.gridx=1;gbc.gridy=0;
con.add(t1,gbc);
//ADDRESS
gbc.gridx=0;gbc.gridy=1;
con.add(l2,gbc);
gbc.gridx=1;gbc.gridy=1;
gbc.fill=GridBagConstraints.RELATIVE;
gbc.fill=GridBagConstraints.BOTH;
con.add(sp1,gbc);
//Telephone
gbc.gridx=0;gbc.gridy=2;
con.add(l3,gbc);
gbc.gridx=1;gbc.gridy=2;
gbc.fill=GridBagConstraints.HORIZONTAL;
con.add(t2,gbc);
//Date Of Birth
gbc.gridx=0;gbc.gridy=3;
con.add(l5,gbc);
gbc.gridx=1;gbc.gridy=3;
con.add(cb1,gbc);
gbc.gridx=2;gbc.gridy=3;
con.add(cb2,gbc);
gbc.gridx=3;gbc.gridy=3;
con.add(cb3,gbc);
//Gender
gbc.gridx=0; gbc.gridy=4;
con.add(l4,gbc);
gbc.gridx=1;gbc.gridy=4;
con.add(r1,gbc);
gbc.gridx=2;gbc.gridy=4;
con.add(r2,gbc);
//Languages Known
gbc.gridx=0;gbc.gridy=5;
con.add(l6,gbc);
gbc.gridx=1;gbc.gridy=5;
con.add(c1,gbc);
gbc.gridx=2;gbc.gridy=5;
con.add(c2,gbc);
gbc.gridx=3;gbc.gridy=5;
con.add(c3,gbc);
//Education Qualification
gbc.gridx=0;gbc.gridy=6;
con.add(l7,gbc);
gbc.gridx=1;gbc.gridy=6;
gbc.gridwidth=2;gbc.gridheight=2;
gbc.fill=GridBagConstraints.BOTH;
con.add(sp2,gbc);
gbc.fill=GridBagConstraints.RELATIVE;
// CMD Buttons
gbc.gridx=1; gbc.gridy=7;
con.add(b1,gbc);
gbc.gridx=2;gbc.gridy=7;
con.add(b2,gbc);
setSize(500,700);
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
public void actionPerformed(ActionEvent ae){
String a,b,c;
a=t1.getText();
b=t2.getText();
c=ta1.getText();
if (ae.getSource()==b1){
if(a.equals(“”)||b.equals(“”)||c.equals(“”)){
JOptionPane.showMessageDialog(this,”Please enter the All the TextBox !!”);}
else
if((r1.isSelected()==false)&&(r2.isSelected()==false)){
JOptionPane.showMessageDialog(this,”Please Select the Gender !!”); }
else
if((c1.isSelected()==false)&&(c2.isSelected()==false)&&(c3.isSelected()==false)){
JOptionPane.showMessageDialog(this,”Please Select the Language Known !!”);}
elseif(ae.getSource()==b1){
JOptionPane.showMessageDialog(this,”BIODATA UPDATED !!”);}
}
if (ae.getSource()==b2){
System.exit(0);}
}
public static void main(String []args){
new biodata();
}}
Practical No. 24
Aim: Write a program on JDBC to store telephone directory and implement all
operations.
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import java.awt.event.*;
import java.util.Vector;
public class friend extends JFrame implements ActionListener{
JLabel lname,lDOB,lAddress,lPhno;
JTextField txtname,txtdob,txtadd,txtphno;
JButton btnadd,btnshow;
Connection dbcon;
Statement st;
String str=””;
ResultSet rs;
public friend(){
Container con=getContentPane();
con.setLayout(null);
con.setBackground(Color.GREEN);
lname=new JLabel(“Friend_Name :-”);
lname.setFont(new Font(“Georgia”,Font.PLAIN,12));
lname.setBounds(20,40,100,25);
add(lname);
lDOB=new JLabel(“DOB :-”);
lDOB.setFont(new Font(“Georgia”,Font.PLAIN,12));
lDOB.setBounds(20,80,100,25);
add(lDOB);
lAddress=new JLabel(“Address :-”);
lAddress.setFont(new Font(“Georgia”,Font.PLAIN,12));
lAddress.setBounds(20,120,100,25);
add(lAddress);
lPhno=new JLabel(“Phno :-”);
lPhno.setFont(new Font(“Georgia”,Font.PLAIN,12));
lPhno.setBounds(20,160,100,25);
add(lPhno);
txtname=new JTextField(20);
txtname.setBounds(150,40,200,25);
add(txtname);
txtdob=new JTextField(20);
txtdob.setBounds(150,80,200,25);
add(txtdob);
txtadd=new JTextField(20);
txtadd.setBounds(150,120,200,25);
add(txtadd);
txtphno=new JTextField(20);
txtphno.setBounds(150,160,200,25);
add(txtphno);
btnadd=new JButton(“SAVE”);
btnadd.addActionListener(this);
btnadd.setBounds(150,200,80,30);
add(btnadd);
btnshow=new JButton(“SHOW”);
btnshow.addActionListener(this);
btnshow.setBounds(250,200,80,30);
add(btnshow);
setVisible(true);
setSize(500,500);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==btnadd){
String a=txtname.getText();
String b=txtdob.getText();
String c=txtadd.getText();
String d=txtphno.getText();
try{
//JOptionPane.showMessageDialog(this, “Record Saved”);
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
dbcon=DriverManager.getConnection(“jdbc:odbc:Friend”);
st=dbcon.createStatement();
JOptionPane.showMessageDialog(this, “Record Saved”);
String sql=”insert into
Dosti1(Name,Dob,Address,Phno)values(‘”+a+”‘,’”+b+”‘,’”+c+”‘,’”+d+”‘)”;
st.executeQuery(sql);
JOptionPane.showMessageDialog(this, “Record Saved”);
}catch(Exception ex){}
}
if(ae.getSource()==btnshow){
Show as=new Show();
}
}
public static void main(String []args){
new friend();
}
class Show extends JDialog{
String mysql;
JTable jt1;
JScrollPane jsp;
int v,h;
Statement st;
ResultSet rs;
Connection dbcon;
JFrame JFParentFrame;
public Show(){
Container con=getContentPane();
con.setLayout(new FlowLayout());
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
dbcon=DriverManager.getConnection(“jdbc:odbc:Friend”);
st =dbcon.createStatement();
mysql=”select * from Dosti1″;
rs=st.executeQuery(mysql);
Vector ch=new Vector();
ch.add(“Name”);
ch.add(“Dob”);
ch.add(“Address”);
ch.add(“Phno”);
Vector data =new Vector();
while(rs.next())
{
Vector row=new Vector();
row.addElement(rs.getString(“Name”));
row.addElement(rs.getString(“Dob”));
row.addElement(rs.getString(“Address”));
row.addElement(rs.getString(“Phno”));
data.addElement(row);
}
jt1=new JTable(data,ch);
}
catch(Exception e){System.out.println(e);
}
v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
jsp=new JScrollPane(jt1,v,h);
con.add(jsp);
setSize(500,500);
setResizable(false);
show();
}
}
}
Practical No. 25
Aim: Write a program on JDBC to store product information and select the product
name and display its bill .
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ResultSetDemo extends JFrame implements ActionListener,ItemListener
{
JButton btnShow;
JLabel lbl,lblQ,lblR,lblT;
JTextField tx1;
JComboBox product;
Connection conn,conn1;
Statement st,st1;
String pr;
int r=0;
public static void main(String[] args)
{
ResultSetDemo r=new ResultSetDemo();
}
ResultSetDemo()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
setVisible(true);
setSize(200,200);
btnShow = new JButton(“Add”);
lbl = new JLabel(“Rate : “);
lblQ = new JLabel(“Quantity”);
lblR = new JLabel();
lblT = new JLabel();
product=new JComboBox();
tx1=new JTextField(20);
//tx2=new JTextField(20);
c.add(product);
c.add(lblQ);
c.add(tx1);
c.add(lbl);
c.add(lblR);
c.add(btnShow);
c.add(lblT);
btnShow.addActionListener(this);
product.addItemListener(this);
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
conn = DriverManager.getConnection(“jdbc:odbc:Phone”);
st = conn.createStatement();
ResultSet rs = st.executeQuery(“select * from Cust”);
String msg=””;
ResultSet rs1 = st.executeQuery(“select * from Products”);
String item;
while(rs1.next())
{
item=rs1.getString(“NameP”);
product.addItem(item);
}
lbl.setText(msg);
rs.close();
st.close();
conn.close();
}
catch (Exception e)
{
}
}
public void itemStateChanged(ItemEvent e)
{
pr=product.getSelectedItem().toString();
String q=”select rate from Products where NameP = ‘”+pr+”‘”;
try
{
conn1 = DriverManager.getConnection(“jdbc:odbc:Phone”);
st1 = conn.createStatement();
ResultSet rs2 = st1.executeQuery(q);
rs2.next();
r=rs2.getInt(“rate”);
}
catch (Exception e11)
{
}
lblR.setText(” “+r);
}
public void actionPerformed(ActionEvent ae)
{
int total=0;
int q=Integer.parseInt(tx1.getText());
total=r*q;
lblT.setText(” “+total);
}
}
Practical No. : 26
Aim: Write a program to implement object serialization and deserialization.
Employee.java
class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println(“Mailing a check to ” + name + ” ” + address); }
}
//SerializeDemo.java
import java.io.*;
class SerializeDemo
{
public static void main(String[] args)
{
Employee e = new Employee();
e.name = “Santosh Goilkar”;
e.address = “Chembur”;
e.SSN = 10;
e.number = 1010;
try
{
FileOutputStream fileOut = new FileOutputStream(“employee.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println(“serealized”);
}
catch (IOException i) { i.printStackTrace();}
}
}
// DeserializeDemo.java
import java.io.*;
class DeserializeDemo
{
public static void main(String[] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream(“employee.ser”);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}
catch (IOException i)
{
i.printStackTrace();
return;
} catch (ClassNotFoundException c)
{
System.out.println(“Employee class not found”);
c.printStackTrace();
return;
}
System.out.println(“Name: ” + e.name);
System.out.println(“Address: ” + e.address);
System.out.println(“SSN: ” + e.SSN);
System.out.println(“Number: ” + e.number);
}
}
/*
Output:
H:\sem 4\Java\done>javac Employee.java
H:\sem 4\Java\done>javac SerializeDemo.java
H:\sem 4\Java\done>java SerializeDemo
serealized
H:\sem 4\Java\done>javac DeserializeDemo.java
H:\sem 4\Java\done>java DeserializeDemo
Name: Santosh Goilkar
Address: Chembur
SSN: 10
Number: 1010
*/
Practical No. 27
Aim: Write a Servlet program for Currency Converter.
Form1.jsp
<!–
To change this template, choose Tools | Templates
and open the template in the editor.
–>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<div>
<form action=”NewServlet” method=”post”>
From Currenct : <Select name=”From”>
<option>Dollar</option>
<option>Rupees</option>
<option>Yen</option>
</select>
<br><br>
Amount : <input type=”text” name=”txtAmt”>
<br><br>
To Currency: <Select name=”To”>
<option>Dollar</option>
<option>Rupees</option>
<option>Yen</option>
</select>
<br><br>
<input type=”submit” value=”btnSubmit”>
</form>
</div>
</body>
</html>
NewServlet.jsp (Servlet)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author student
*/
@WebServlet(name = “NewServlet”, urlPatterns = {“/NewServlet”})
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
String amt = request.getParameterValues(“txtAmt”)[0];
String from = request.getParameterValues(“From”)[0];
String to = request.getParameterValues(“To”)[0];
double amt1;
double ans=0.0;
amt1=Double.parseDouble(amt);
if (“”.equals(amt))
{
ans=0;
}
else if(“Dollar”.equals(from) && “Dollar”.equals(to))
{
ans=amt1;
}
else if(“Rupees”.equals(from) && “Rupees”.equals(to))
{
ans=amt1;
}
else if(“Yen”.equals(from) && “Yen”.equals(to))
{
ans=amt1;
}
else if(“Dollar”.equals(from) && “Yen”.equals(to))
{
ans=amt1/25;
}
else if(“Yen”.equals(from) && “Dollar”.equals(to))
{
ans=amt1*25;
}
else if(“Yen”.equals(from) && “Rupees”.equals(to))
{
ans=amt1*65;
}
else if(“Rupees”.equals(from) && “Yen”.equals(to))
{
ans=amt1/65;
}
else if(“Dollar”.equals(from) && “Rupees”.equals(to))
{
ans=amt1*60;
}
else if(“Rupees”.equals(from) && “Yen”.equals(to))
{
ans=amt1/66;
}
else
{
ans=0;
}
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet NewServlet</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<h1>Amout is ” + ans + “</h1>”);
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
// <editor-fold defaultstate=”collapsed” desc=”HttpServlet methods. Click on the + sign on
the left to edit the code.”>
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
}
Practical No. 28
Aim: Write a Servlet program for quiz assignment.
//index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<html>
<head>
<title>multiple-choice quiz form</title>
</head>
<body bgcolor=#ffffff>
<h3>Cryptography Quiz </h3>
<form method=”post” action=”Quiz”>
<BR>Enter your Name : <input type=”text” name=”name” value=””><BR>
<P>1. In cryptography, what is cipher?<BR>
<input type=”radio” name=”1″ value=”A”>
A. algorithm for performing encryption and decryption<BR>
<input type=”radio” name=”1″ value=”B”>B. encrypted message<BR>
<input type=”radio” name=”1″ value=”C”>C. both (a) and (b)<BR>
<input type=”radio” name=”1″ value=”D”>D. none of the mentioned<BR>
</p>
<P>2. The ________ is the message after transformation.<BR>
<input type=”radio” name=”2″ value=”A”>A. cipher text<BR>
<input type=”radio” name=”2″ value=”B”>B. plain text<BR>
<input type=”radio” name=”2″ value=”C”>C. secret text<BR>
<input type=”radio” name=”2″ value=”D”>D. none of the above<BR>
</p>
<P>3. A(n) ______ algorithm transforms cipher text to plaintext.<BR>
<input type=”radio” name=”3″ value=”A”>A. encryption<BR>
<input type=”radio” name=”3″ value=”B”>B. decryption<BR>
<input type=”radio” name=”3″ value=”C”>C. either (a) or (b)<BR>
<input type=”radio” name=”3″ value=”D”>D. neither (a) nor (b)<BR>
</p>
<P>4. The _______ is a number or a set of numbers on which the cipher operates.<BR>
<input type=”radio” name=”4″ value=”A”>A. cipher<BR>
<input type=”radio” name=”4″ value=”B”>B. secret<BR>
<input type=”radio” name=”4″ value=”C”>C. key<BR>
<input type=”radio” name=”4″ value=”D”>D. none of the above<BR>
</p>
<P>5. A combination of an encryption algorithm and a decryption algorithm is called a
________.<BR>
<input type=”radio” name=”5″ value=”A”>A. cipher<BR>
<input type=”radio” name=”5″ value=”B”>B. secret<BR>
<input type=”radio” name=”5″ value=”C”>C. key<BR>
<input type=”radio” name=”5″ value=”D”>D. none of the above<BR>
</p>
<br><br>
<input type=”submit” value=”Send Form”>
<input type=”reset” value=”Clear Form”>
</form>
</body>
</html>
// Quiz.java
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 NewServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name1 = request.getParameter(“name”);
String a1 = request.getParameter(“1″);
String a2 = request.getParameter(“2″);
String a3 = request.getParameter(“3″);
String a4 = request.getParameter(“4″);
String a5 = request.getParameter(“5″);
int cnt = 0;
if (a1.equals(“A”)) {
cnt++;
}
if (a2.equals(“A”)) {
cnt++;
}
if (a3.equals(“B”)) {
cnt++;
}
if (a4.equals(“C”)) {
cnt++;
}
if (a5.equals(“A”)) {
cnt++;
}
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<html><head>”);
out.println(“<title>Cryptography Quiz</title>”);
out.println(“</head><body><br><br><br><br>”);
out.println(“<Center><h1>Hi ” + name1 + “, you have got ” + cnt + “
score in Cryptography Quiz</h1><Center>”);
out.println(“</body></html>”);
out.close();
}}
Program No: 29
Aim : Write a servlet program to retrieve event based on date from database
//index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<html><body>
<form method=post action=schedule>
<br><br><br>
<center>
Enter Date: <input type=”text” name=”sdate” value=””>
<br><br>
<input type=”submit” value=”Submit”>
</center>
</form>
</body>
</html>
// schedule.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class schedule extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String sdate = request.getParameter(“sdate”);
String details = “”;
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:testx”, “”, “”);
java.sql.Statement smt = con.createStatement();
ResultSet res = smt.executeQuery(“Select Event from timetable where Tdate=’” + sdate +
“‘”);
if (res.next()) {
details = res.getString(1);
} else {
details = “Holiday”;
}
} catch (Exception e) {
}
out.println(“<html><head>”);
out.println(“<title>Time Table</title>”);
out.println(“</head><body><br><br><br><br>”);
out.println(“<Center><h1>On ” + sdate + “, There will be ” + details + “</h1><Center>”);
out.println(“</body></html>”);
out.close();
}}
Program No: 30
Aim : Write a servlet program to HttpSession (Web Page Counter).
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
int cnt = 1;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession hs = request.getSession(true);
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Date date = (Date) hs.getAttribute(“date”);
if (date != null) {
pw.print(“Last access: ” + date);
pw.print(“<br>Last Web page count: ” + cnt + “<br><br>”);
}
date = new Date();
hs.setAttribute(“date”, date);
cnt = cnt + 1;
pw.println(“Current date: ” + date);
pw.print(“<br>Current Web page count: ” + cnt + “<br>”);
}
}
Program No: 31
Aim : Develop a JSP page for Grade Calculator.
<%–
Document : frm1
Created on : Apr 15, 2014, 10:29:59 PM
Author
: SAMIKSHA
–%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<h2>Student Grading System</h2>
<form action=”” method=”post”>
<table>
<tr>
<td></td>
<td>
Select Course <select name=”course”>
<option value=”select”>select</option>
<option value=”MCA”>MCA</option>
<option value=”BCA”>BCA</option>
</select>
</td>
</tr>
</table>
<table>
<tr>
<th>Subject</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
</tr>
<tr>
<td align=”center”>Core & Advanced JAVA</td>
<td align=”center”><input type=”text” size=”5″ name=”c”/></td>
<td align=”center”>100</td>
</tr>
<tr>
<td align=”center”>ADTA</td>
<td align=”center”><input type=”text” size=”5″ name=”java”/></td>
<td align=”center”>100</td>
</tr>
<tr>
<td align=”center”>SMS</td>
<td align=”center”><input type=”text” size=”5″ name=”net”/></td>
<td align=”center”>100</td>
</tr>
<tr>
<td align=”center”>>HCI</td>
<td align=”center”><input type=”text” size=”5″ name=”vb”/></td>
<td align=”center”>100</td>
</tr>
<tr>
<td align=”center”>Lab I & II</td>
<td align=”center”><input type=”text” size=”5″ name=”dbms”/></td>
<td align=”center”>100</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr><td></td><td align=”center”><input type=”submit” value=”submit”/></td></tr>
</table>
</form>
<%
String c = request.getParameter(“c”);
String j = request.getParameter(“java”);
String n = request.getParameter(“net”);
String v = request.getParameter(“vb”);
String d = request.getParameter(“dbms”);
if(!(c == null || c.isEmpty()))
{
int cmarks = Integer.parseInt(c);
int jmarks = Integer.parseInt(j);
int nmarks = Integer.parseInt(n);
int vmarks = Integer.parseInt(v);
int dmarks = Integer.parseInt(d);
int total = cmarks+jmarks+nmarks+vmarks+dmarks;
int avg = (total)/5;
int percent = avg;
String grade =””;
if(percent < 40){
grade = “E”;
//request.setAttribute(“grade”, grade);
}
else if(percent >= 40 && percent <=44){
grade = “D”;
}
else if(percent >=45 && percent <=49){
grade = “D+”;
}
else if(percent >=50 && percent <=54){
grade = “C-”;
}
else if(percent >=55 && percent<=59){
grade = “C”;
}
else if(percent >=60 && percent <=64){
grade = “C+”;
}
else if(percent >=65 && percent<=69){
grade = “B-”;
}
else if(percent >=70 && percent <=74){
grade = “B”;
}
else if(percent >=75 && percent <=79){
grade = “B+”;
}
else if(percent >=80 && percent <=84){
grade = “A”;
}
else if (percent >=85 && percent <=100){
grade = “A+”;
}
request.setAttribute(“Grade”, grade);
%>
<table>
<tr>
<td><b>Course</b></td><td></td>
<td align=”center”><%=request.getParameter(“course”) %>
</tr>
<tr>
<td><b>Aggregate Marks</b></td><td></td>
<td align=”center”><%=total %></td>
</tr>
<tr>
<td><b>Grade</b></td><td></td>
<td align=”center”><%=grade %></td>
</tr>
</table>
<%
}
%>
Program No: 32
Aim : Develop a JSP page using Cookies.
Page1.html
<html>
<head>
<title></title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form name=”f1″ method=”POST” action=”page2.jsp”>
<center>
Name : <input type=”text” name=”txtname”>
<br><br>
<input type=”submit” value=”Submit”>
</center>
</form>
</body>
</html>
Page2.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
Cookie Name = new Cookie(“name”,request.getParameter(“txtname”));
Name.setMaxAge(60*60*24);
response.addCookie( Name );
%>
<center> <a href=”page2.jsp”>Read Cookie</a></center>
</body>
</html>
Page2.html
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
out.println(c[i].getName());
out.println(c[i].getValue());
}
%>
</body>
</html>
Program No: 33
Aim : Develop a JSP page for session management.
//index.jsp
<%@ page import=”java.io.*,java.util.*” %>
<% Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = “Welcome Back to my website”;
Integer visitCount = new Integer(0);
String visitCountKey = new String(“visitCount”);
String userIDKey = new String(“userID”);
String userID = new String(“BVIMIT”);
if (session.isNew()) {
title = “Welcome to my website”;
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String) session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);%>
<html>
<body>
<center><h1>Session Tracking</h1></center>
<table border=”1″ align=”center”>
<tr bgcolor=”#949494″>
<th>Session info</th><th>Value</th>
</tr>
<tr><td>id</td>
<td><% out.print(session.getId());%></td>
</tr>
<tr><td>Creation Time</td>
<td><% out.print(createTime);%></td>
</tr>
<tr><td>Time of Last Access</td>
<td><% out.print(lastAccessTime);%></td>
</tr>
<tr><td>User ID</td>
<td><% out.print(userID);%></td>
</tr>
<tr><td>Number of visits</td>
<td><% out.print(visitCount);%></td>
</tr>
</table>
</body></html>
//Output:
Program No: 34
Aim : Develop a JSP page for error handling.
login.html
<html>
<head>
<title></title>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form name=”f1″ method=”POST” action=”errordemo.jsp”>
<center>
User Name : <input type=”text” name=”name”><br><br>
Password : <input type=”password” name=”pwd”><br><br>
<input type=”submit” value=”Submit”>
</center>
</form>
</body>
</html>
Welcome.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
Object n=session.getAttribute(“name”);
String ns=n.toString();
%>
<h1>welcome to the page <%=ns%></h1>
</body>
</html>
ErrorPage.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@page isErrorPage=”true”%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<h1>Invalid Username or password</h1>
</body>
</html>
Errordemo.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@page errorPage=”errorpage.jsp” session=”true”%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
String n=request.getParameter(“name”);
String p=request.getParameter(“pwd”);
if(n.equals(“abc”) && p.equals(“xyz”))
{
session.setAttribute(“name”, n);
session.setAttribute(“pwd”, p);
<jsp:forward page=”welcome.jsp”/>
}
else
{
response.sendRedirect(“errorpage.jsp”);
}
%>
</body>
</html>
Login.html
errorDemo.jsp
Errorpage.jsp
Program No: 36
Aim : Develop a JSP page using for login authentication using JDBC.
//index.html
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Login Form</h1>
<form action=”login.jsp” method=”post” >
<br>User Name :<input type=”text” name=”uname”>
<br>Password :<input type=”password” name=”pass”>
<br><input type=”submit” value=”Login”>\
</form></body>
</html>
//login.jsp
<%@page import=”java.sql.DriverManager”%>
<%@page import=”java.sql.ResultSet”%>
<%@page import=”java.sql.Statement”%>
<%@page import=”java.sql.Connection”%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html><head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head><body><h2>
<%
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:testx”, “”, “”);
Statement smt = con.createStatement();
String uname = request.getParameter(“uname”);
String pass = request.getParameter(“pass”);
ResultSet res = smt.executeQuery(“Select * from login where uname=’” + uname + “‘ and
pass=’” + pass + “‘ “);
if (res.next()) {
out.println(“User ” + uname + ” Successfully logged in… “);
} else {
out.println(“Enter proper login detail..”);
}
} catch (java.lang.Exception ex) { out.println(“Error in connection”);
}
%>
</h2>
</body></html>
//Output:
Program No: 37
Aim : Write a program on Session bean (stateless , stateful)
//calculatorBeanLocal.java
package sample.ejb;
import javax.ejb.Local;
@Local
public interface calculatorBeanLocal {
Integer beanAdd(int a, int b);
Integer beansub(int a, int b);
}
//calculatorBeanLocal.java
package sample.ejb;
import javax.ejb.Stateless;
@Stateless
public class calculatorBean implements calculatorBeanLocal {
@Override
public Integer beanAdd(int a, int b) {
return (a + b);
}
public Integer beansub(int a, int b) {
return (a – b);
}
}
//Index.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form action=SessionBeanServlet>
<input type=”submit”>
</form>
</body>
</html>
//SessionBeanServlet.java
package sample.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sample.ejb.calculatorBeanLocal;
@WebServlet(name = “SessionBeanServlet”, urlPatterns = {“/SessionBeanServlet”})
public class SessionBeanServlet extends HttpServlet {
@EJB
private calculatorBeanLocal calculatorBean;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
try {
int a = 9;
int b = 3;
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet SessionBeanServlet</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<br>Addition of two number is ” + calculatorBean.beanAdd(a, b));
out.println(“<br>Subtraction of two number is ” + calculatorBean.beansub(a, b));
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
}
Output:
Program No:38
Aim : Write a program on Message Driven bean.
//NewServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = “NewServlet”, urlPatterns = {“/NewServlet”})
public class NewServlet extends HttpServlet {
@Resource(mappedName = “jms/dest”)
private Queue dest;
@Resource(mappedName = “jms/queue”)
private ConnectionFactory queue;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
String str = request.getParameter(“msg”);
try {
out.println(“<html>”);
out.println(“<head>”);
out.println(“</head>”);
out.println(“<body>”);
try {
sendJMSMessageToDest(str);
} catch (JMSException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
out.println(“<h1> Your Message ” + str + ” has been send to server </h1>”);
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
private Message createJMSMessageForjmsDest(Session session, Object messageData)
throws JMSException {
// TODO create and populate message to send
TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
}
private void sendJMSMessageToDest(Object messageData) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = queue.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(dest);
messageProducer.send(createJMSMessageForjmsDest(session, messageData));
} finally {
if (session != null) {
try {
session.close();
} catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, “Cannot close session”,
e);
}
}
if (connection != null) {
connection.close();
}
}
}
}
//Enterprise Beans MBean
package com.message;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(mappedName = “jms/dest”, activationConfig = {
@ActivationConfigProperty(propertyName = “acknowledgeMode”, propertyValue = “Autoacknowledge”),
@ActivationConfigProperty(propertyName = “destinationType”, propertyValue =
“javax.jms.Queue”)
})
public class MBean implements MessageListener {
public MBean() {
}
@Override
public void onMessage(Message message) {
try {
TextMessage tmsg=null;
tmsg=(TextMessage)message;
System.out.println(tmsg.getText());
} catch (JMSException ex) {
Logger.getLogger(MBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Index.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form action=’NewServlet’>
<h1> Enter Your Message <input type=”text” name=”msg”>
<input type=”submit”>
</h1></form>
</body>
</html>
//Output:
Program No:39
Aim : Write a program on entity bean.
//AbstractFacade.java
package mypack;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] – range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}}
//Emp.java
package mypack;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = “EMP”)
@XmlRootElement
@NamedQueries({
@NamedQuery(name = “Emp.findAll”, query = “SELECT e FROM Emp e”),
@NamedQuery(name = “Emp.findByEmpno”, query = “SELECT e FROM Emp e WHERE
e.empno = :empno”),
@NamedQuery(name = “Emp.findByEname”, query = “SELECT e FROM Emp e WHERE
e.ename = :ename”)})
public class Emp implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = “EMPNO”)
private Integer empno;
@Size(max = 20)
@Column(name = “ENAME”)
private String ename;
public Emp() {
}
public Emp(Integer empno) {
this.empno = empno;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
@Override
public int hashCode() {
int hash = 0;
hash += (empno != null ? empno.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Emp)) {
return false;
}
Emp other = (Emp) object;
if ((this.empno == null && other.empno != null) || (this.empno != null &&
!this.empno.equals(other.empno))) {
return false;
}
return true;
}
@Override
public String toString() {
return “mypack.Emp[ empno=" + empno + " ]“;
}
}
//EmpFacade.java
package mypack;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class EmpFacade extends AbstractFacade<Emp> implements EmpFacadeLocal {
@PersistenceContext(unitName = “EBean-ejbPU”)
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public EmpFacade() {
super(Emp.class);
}
@Override
public void persist(Object obj) {
em.persist(obj);
}
@Override
public void addsEmp(int eid, String ename) {
Emp obj = new Emp();
obj.setEmpno(eid);
obj.setEname(ename);
persist(obj);
}}
//EmpFacadeLocal.java
package mypack;
import java.util.List;
import javax.ejb.Local;
@Local
public interface EmpFacadeLocal {
void create(Emp emp);
void edit(Emp emp);
void remove(Emp emp);
Emp find(Object id);
List<Emp> findAll();
List<Emp> findRange(int[] range);
int count();
public void persist(java.lang.Object obj);
public void addsEmp(int eid, String ename);
}
//empEntity.java
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class empEntity extends HttpServlet {
@EJB
private EmpFacadeLocal empFacade;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
try {
empFacade.addsEmp(11, “Santosh”);
empFacade.addsEmp(12, “Tejas”);
empFacade.addsEmp(13, “Prasad”);
empFacade.addsEmp(14, “Nagesh”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet NewServlet</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<h1>Record inserted successfully” + “</h1>”);
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}}
//Output:
Program No:40
Aim : Write program on struts.
//register.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”s” uri=”/struts-tags” %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Registration Form</h1>
<s:form action=”registerAction”>
<s:textfield name=”id” label=”Enter id :”>
</s:textfield>
<s:textfield name=”uname” label=”Enter Username :”>
</s:textfield>
<s:password name=”upass” label=”Enter Password :”>
</s:password>
<s:textfield name=”email” label=”Enter Email-id :”>
</s:textfield>
<s:textfield name=”age” label=”Enter Age:”>
</s:textfield>
<s:submit value=”Submit”>
</s:submit>
</s:form>
</body>
</html>
//login.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Well come <%=request.getParameter(“uname”)%> ,</h1>
</body>
</html>
//error.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Error Catch.</h1>
</body>
</html>
//struts.xml
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>
<struts>
<!– Configuration for the default package. –>
<package name=”default” extends=”struts-default” namespace=”/”>
<action name=”registerAction” class=”com.myapp.mode.Action.RegisterActionSupport”>
<result name=”input”>/register.jsp </result>
<result name=”success”>/login.jsp </result>
<result name=”error”>/error.jsp </result>
</action>
</package>
</struts>
//RegisterActionSupport-validation.xml
<!DOCTYPE validators PUBLIC
“-//Apache Struts//XWork Validator 1.0.2//EN”
“http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd”>
<validators>
<field name=”id”>
<field-validator type=”requiredstring”>
<message>
The id is required.
</message>
</field-validator>
</field>
<field name=”uname”>
<field-validator type=”requiredstring”>
<message>
The name is required.
</message>
</field-validator>
</field>
<field name=”upass”>
<field-validator type=”requiredstring”>
<message>
The pass is required.
</message>
</field-validator>
</field>
<field nme=”email”>
<field-validator type=”requiredstring”>
<message>
email is required.
</message>
</field-validator>
<field-validator type=”email”>
<message>
email is invalid.
</message>
</field-validator>
</field>
<field name=”age”>
<field-validator type=”required”>
<message>You must enter a value for age.</message>
</field-validator>
<field-validator type=”int”>
<param name=”min”>6</param>
<param name=”max”>20</param>
<message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
</field-validator>
</field>
</validators>
//RegisterActionSupport.java
package com.myapp.mode.Action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterActionSupport extends ActionSupport {
private String id, uname;
public int getAge() {
return age;
public void setAge(int age) {
public String getEmail() {
}
this.age = age;
return email;
public void setEmail(String email) {
public String getId() {
return id;
public void setId(String id) {
public String getUname() {
}
this.email = email;
}
}
this.id = id;
}
return uname; }
public void setUname(String uname) {
public String getUpass() {
}
this.uname = uname;
return upass;
public void setUpass(String upass) {
}
this.upass = upass;
private String upass;
private String email;
private int age;
public RegisterActionSupport() {
}
@Override
public String execute() throws Exception {
}
}
return SUCCESS;
}
}
//Output:
JAVA-A
/* Write a program to demonstrate Single Inheritance */
Practical No.:
class squre
{
private int length,breath;
squre(int l,int b)
{
length=l;
breath=b;
}
public double area() { return(length*breath); }
}
class cube extends squre
{
private int height;
cube(int l,int b,int h)
{
super(l,b);
height=h;
}
public double volume() {return(area()*height);}
Date:
}
class singleinheritance
{
public static void main(String args[])
{
cube c=new cube(10,20,2);
System.out.println(“Area of Squre = “+c.area());
System.out.println(“Volume of cube = “+c.volume());
}
}
Output:
F:\mca\sem 4\Java>javac singleinheritance.java
F:\mca\sem 4\Java>java singleinheritance
Area of Squre = 200.0
Volume of cube = 400.0
/* Write a program to demonstrate Multilevel Inheritance */
Practical No.:
class shape
{
Date:
private int width,height;
public int getwidth() { return width; }
public int getheight(){ return height;}
shape(int w,int h)
{
width=w;
height=h;
}
public void show()
{
System.out.println(“Shape width= “+width);
System.out.println(“Shape Heighth= “+height);
}
}
class triangle extends shape
{
private String style;
triangle(int w,int h,String s)
{
super(w,h);
style=s;
}
public double area(){return(0.5*getwidth()*getheight());}
public void showstyle()
{
System.out.println(“Triangle area= “+area());
System.out.println(“Triangle Style= “+style);
}
}
class colortriangle extends triangle
{
private String color;
colortriangle(int w,int h,String s,String c)
{
super(w,h,s);
color=c;
}
public void showcolor()
{
System.out.println(“Triangle color= “+color);
}
}
class multilevel
{
public static void main(String args[])
{
colortriangle t=new colortriangle(10,10,”Bilateral Triangle”,”Red”); // object of class
colortriangle
t.show();
// class shape function
t.showstyle();
// class triangle function
t.showcolor(); // class colortriangle function
}
}
Output:
F:\mca\sem 4\Java>javac multilevel.java
F:\mca\sem 4\Java>java multilevel
Shape width= 10
Shape Heighth= 10
Triangle area= 50.0
Triangle Style= Bilateral Triangle
Triangle color= Red
/* Write a program to demonstrate Hierarchical Inheritance */
Practical No.:
class emp
{
private int empid,sal;
private String ename,designation,qualification;
Date:
emp(int id,String name,int s,String desgn,String qul)
{
empid=id;
ename=name;
sal=s;
designation=desgn;
qualification=qul;
}
public void display()
{
System.out.println(“Emp ID= “+empid);
System.out.println(“Emp Name= “+ename);
System.out.println(“Emp Salary= “+sal);
System.out.println(“Emp Designation= “+designation);
System.out.println(“Emp Qualification= “+qualification);
}
}
class teaching extends emp
{
private String Subjects;
teaching(int id,String name,int salamt,String desgn,String qul,String s)
{
super(id,name,salamt,desgn,qul);
Subjects=s;
}
public void displayteaching()
{
System.out.println(“Teaching Staff Details”);
display();
System.out.println(“Emp Subject= “+Subjects);
}
}
class nonteaching extends emp
{
private String type;
nonteaching(int id,String name,int salamt,String desgn,String qul,String t)
{
super(id,name,salamt,desgn,qul);
type=t;
}
public void displaynonteaching()
{
System.out.println(“Non Teaching Staff Details”);
display();
System.out.println(“Emp Type= “+type);
}
}
class hierarchicalheritance
{
public static void main(String args[])
{
teaching t=new teaching(10,”Santosh”,10000,”Prof.”,”MCA”,”Java”);
nonteaching nt=new nonteaching(20,”Priya”,1000,”Cleark”,”B.Sc.”,”Permanant”);
t.displayteaching();
nt.displaynonteaching();
}
}
Output:
F:\mca\sem 4\Java>javac hierarchicalheritance.java
F:\mca\sem 4\Java>java hierarchicalheritance
Teaching Staff Details
Emp ID= 10
Emp Name= Santosh
Emp Salary= 10000
Emp Designation= Prof.
Emp Qualification= MCA
Emp Subject= Java
Non Teaching Staff Details
Emp ID= 20
Emp Name= Priya
Emp Salary= 1000
Emp Designation= Cleark
Emp Qualification= B.Sc.
Emp Type= Permanent
/* Write a program to demonstrate Hybrid Inheritance */
Practical No.:
class staff
{
private int scode;
private String name;
staff(int c,String n)
{
scode=c;
name=n;
}
public void display_staff()
{
System.out.println(“Staff Code= “+scode);
System.out.println(“Staff Name= “+name);
}
}
class teacher extends staff
{
private String subject,publication;
Date:
teacher(int c,String n,String s,String p)
{
super(c,n);
subject=s;
publication=p;
}
public void display_teacher()
{
System.out.println(“\n Teaching Staff Details”);
display_staff();
System.out.println(“Staff Subject= “+subject);
System.out.println(“Staff Publication= “+publication);
}
}
class typist extends staff
{
private String speed;
typist(int c,String n,String s)
{
super(c,n);
speed=s;
}
public void display_typist()
{
display_staff();
System.out.println(“Staff Typing Speed= “+speed);
}}
class regular extends typist
{
private double salary;
regular(int c,String n,String s,double sal)
{
super(c,n,s);
salary=sal;
}
public void display_regular()
{
System.out.println(“\n Regular Typing Staff Details”);
display_typist();
System.out.println(“Regular Staff Salary= “+salary);
}
}
class casual extends typist
{
private double charges;
casual(int c,String n,String s,double chr)
{
super(c,n,s);
charges=chr;
}
public void display_casual()
{
System.out.println(“\n Casual Typing Staff Details”);
display_typist();
System.out.println(“Casual Staff charges= “+charges);
}
}
class officer extends staff
{
private String grade;
officer(int c,String n,String g)
{
super(c,n);
grade=g;
}
public void display_officer()
{
System.out.println(“\n Officer Staff Details”);
display_staff();
System.out.println(“Staff officer grade= “+grade);
}
}
class educational
{
public static void main(String args[])
{
teacher t=new teacher(10,”Santosh”,”.net”,”TMH”);
t.display_teacher();
regular r=new regular(20,”Priya”,”70 WPM”,15000);
r.display_regular();
casual c=new casual(30,”Kunal”,”70 WPM”,1000);
c.display_casual();
officer o=new officer(30,”Sai”,”A1 Grade”);
o.display_officer();
}
}
Output:
F:\mca\sem 4\Java>javac educational.java
F:\mca\sem 4\Java>java educational
Teaching Staff Details
Staff Code= 10
Staff Name= Santosh
Staff Subject= .net
Staff Publication= TMH
Regular Typing Staff Details
Staff Code= 20
Staff Name= Priya
Staff Typing Speed= 70 WPM
Regular Staff Salary= 15000.0
Casual Typing Staff Details
Staff Code= 30
Staff Name= Kunal
Staff Typing Speed= 70 WPM
Casual Staff charges= 1000.0
Officer Staff Details
Staff Code= 30
Staff Name= Sai
Staff officer grade= A1 Grade
/* Write a program to display Armstrong number, factorial number, palindrome
number, and prime number using switch case */
Practical No.:
import java.io.*;
class all_operation
{
public void Armstrong(int no)
{
int num=no,temp,sum=0;
while(num!=0)
{
temp = num % 10 ;
sum=sum+(temp*temp*temp);
num = num / 10 ;
}
if(sum==no)
Date:
System.out.println(“The no “+no+” is Armstrong number.”);
else
System.out.println(“The no “+no+” is not Armstrong number.”);
}
public void Prime(int no)
{
int i=2,flag=0;
do
{
if(no%i==0)
{
System.out.println(“The no “+no+” is not prime number.”);
flag=1;
break;
}
i=i+1;
}while(i<(no/2));
if(flag==0)
System.out.println(“The no “+no+” is prime number.”);
}
public void Factorial(int no)
{
int i;
double fact=1;
if(no<0)
fact=-1;
if((no==0)||(no==1))
fact=1;
else
for(i=2;i<=no;i++)
fact=fact*i;
System.out.println(“The factorial of “+no+” is “+fact);
}
public void Palindrome(int no)
{
int num=no,temp,sum=0,t=1;
while(num!=0)
{
t=t*10;
num = num / 10 ;
}
num=no;
while(num!=0)
{
temp = num % 10 ;
t=t/10;
sum=sum+temp*t;
num = num / 10 ;
}
if(sum==no)
System.out.println(“The no “+no+” is Palindrome number.”);
else
System.out.println(“The no “+no+” is not Palindrome number.”);
}}
class operations
{
public static void main(String args[]) throws IOException
{
all_operation o=new all_operation();
DataInputStream in=new DataInputStream(System.in);
int a,c;
char choice;
do
{
try{
System.out.println(“\n Enter the number”);
a=Integer.parseInt(in.readLine());
System.out.println(“\n Enter choice 1 for Armstrong no. :”);
System.out.println(“\n Enter choice 2 for Factorial no. :”);
System.out.println(“\n Enter choice 3 for Palindrome no. :”);
System.out.println(“\n Enter choice 4 for Prime no. :”);
System.out.println(“\n Enter your choice :”);
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1 :
o.Armstrong(a);
break;
case 2 :
o.Factorial(a);
break;
case 3 :
o.Palindrome(a);
break;
case 4 :
o.Prime(a);
break;
default :
System.out.println(“wrong choices .”);
System.out.println(“\n Enter right choice :”);
break;
}
}catch(Exception e){}
System.out.println(” \tDo you want to continue (y/n):- “);
choice=in.readLine().charAt(0);
}while(choice!=’n’);
}}
/*
output:
H:\sem 4\Java>javac operations.java
H:\sem 4\Java>java operations
Enter the number 121
Enter choice 1 for Armstrong no. :
Enter choice 2 for Factorial no. :
Enter choice 3 for Palindrome no. :
Enter choice 4 for Prime no. :
Enter your choice : 3
The no 121 is Palindrome number.
Do you want to continue (y/n):- y
Enter the number 153
Enter choice 1 for Armstrong no. :
Enter choice 2 for Factorial no. :
Enter choice 3 for Palindrome no. :
Enter choice 4 for Prime no. :
Enter your choice : 1
The no 153 is Armstrong number.
Do you want to continue (y/n):- y
Enter the number 5
Enter choice 1 for Armstrong no. :
Enter choice 2 for Factorial no. :
Enter choice 3 for Palindrome no. :
Enter choice 4 for Prime no. :
Enter your choice : 2
The factorial of 5 is 120.0
Do you want to continue (y/n):-y
Enter the number 7
Enter choice 1 for Armstrong no. :
Enter choice 2 for Factorial no. :
Enter choice 3 for Palindrome no. :
Enter choice 4 for Prime no. :
Enter your choice : 4
The no 7 is prime number.
Do you want to continue (y/n):-n
*/
/*Write a program to take command line input display features of java */
Practical No.:
class features
{
public static void main(String[] args)
{
Date:
System.out.println(“Features of java are “);
for(int p=0;p<args.length;p++)
{
System.out.print(args[p]+”, “);
}
}
}
/*
Output:
H:\sem 4\Java\done>javac features.java
H:\sem 4\Java\done>java features Simple Secure Portable Object-oriented Robust
Features of java are Simple, Secure, Portable, Object-oriented, Robust,
*/
/*Write a program to create a class room area which will calculate area of room.
Overload the constructors for required parameters*/
Practical No.:
import java.io.*;
class roomarea
Date:
{
private int l,b;
roomarea ()
{l=0;b=0;}
roomarea (int i,int j)
{l=i;b=j;}
public double area(roomarea o)
{
return(o.l*o.b);
}
public double area(int i,int j)
{
return(i*j);
}
}
class arearesult
{
public static void main(String[] args)
{
roomarea o1=new roomarea();
roomarea o2=new roomarea(10,20);
System.out.println(“Room Area=”+o1.area(o2));
System.out.println(“Room Area=”+o1.area(10,20));
}}
/*
Output:
H:\sem 4\Java\done>javac arearesult.java
H:\sem 4\Java\done>java arearesult
Room Area=200.0
Room Area=200.0
*/
/* Write a program that initializes an int variable and with value 5815 & used the
quotient & remainder operator to extract & print each digit of n.*/
Practical No.:
class separate
{
public static void main(String[] args)
{
int i=5815,t=1000,k=0;
String j=””;
while(i>0)
{
k=i/t;
i=i%t;
Date:
t=t/10;
j=j+k+”, “;
}
System.out.print(“Given Number is 5815 and separate digits in number are “+j);
}
}
/*
Output:
H:\sem 4\Java\done>javac separate.java
H:\sem 4\Java\done>java separate
Given Number is 5815 and separate digits in number are 5, 8, 1, 5,
*/
/* Write a program to display following output.*/
Practical No.:
import java.io.*;
class array2d
{
public static void main(String[] args) throws IOException
Date:
{
int[][] a = new int[4][5];
int i=0,j=0,k=0;
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=k;k=k+1;
}
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
System.out.print(“\t”+a[i][j]);
}
System.out.println(“”);
}
} }
/*
Output:
H:\sem 4\Java\done>javac array2d.java
H:\sem 4\Java\done>java array2d
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
*/
/*Write Program which will have a class encaptest which will accept name, age use
getter and setter method as per required*/
Practical No.:
class encaptest
{
private String n;
private int age;
public String getname() {return n;}
public int getage() {return age;}
public void setname(String newname ) {n=newname;}
public void setage(int newage ) {age=newage;}
}
Date:
class runencap
{
public static void main(String[] args)
{
encaptest o=new encaptest ();
o.setname(“Santosh”);
o.setage(22);
System.out.println(“Name = “+o.getname()+” Age = “+o.getage());
}
}
/*
Output:
H:\sem 4\Java\done>javac runencap.java
H:\sem 4\Java\done>java runencap
Name = Santosh Age = 22
*/
/* Write Program which will have a class circle which will accept the radius and
calculate diameter, circumference of circle*/
Practical No.:
Date:
import java.io.*;
class circle
{
int radius;
public void get_radius() throws IOException
{
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter the radius of circle”);
radius=Integer.parseInt(dr.readLine());
}
public int cal_diameter()
{return(2*radius);}
public double cal_circumference()
{return(2*radius*3.14);}
}
class runcircle
{
public static void main(String[] args) throws IOException
{
circle r=new circle();
r.get_radius();
System.out.println(“Diameter of circle is “+r.cal_diameter());
System.out.println(“Circumference of circle is “+r.cal_circumference());
}}
/*
Output:
H:\sem 4\Java\done>javac runcircle.java
H:\sem 4\Java\done>java runcircle
Enter the radius of circle: 15
Diameter of circle is 30
Circumference of circle is 94.2
*/
/* Write a program to store days of month display no of days for suitable month */
Practical No.:
import java.io.*;
class month_days
{
public static void main(String[] args) throws IOException
{
String [] month ={“Jan”,”Feb”,”March”,”Apr”,”May”,
Date:
“June”,”July”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”};
int days []={31,28,31,30,31,30,31,31,30,31,30,31};
int i;
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter the Month Number :”);
i=Integer.parseInt(dr.readLine());
System.out.println(“Month “+month[i-1]+” is having days = “+days[i-1]);
}
}
/*
Output:
H:\sem 4\Java\done>javac month_days.java
H:\sem 4\Java\done>java month_days
Enter the Month Number : 11
Month Nov is having days = 30
*/
/*Write a program which will display multiplication table for number n*/
Practical No.:
import java.io.*;
class multiplication
{
public static void main(String[] args) throws IOException
{
int n;
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter the number for multiplication table:”);
n=Integer.parseInt(dr.readLine());
System.out.println(“Multiplication table of “+n+” is :”);
for(int i=1;i<=10;i++)
System.out.println(i*n);
}
}
/*
Output:
H:\sem 4\Java\done>javac multiplication.java
H:\sem 4\Java\done>java multiplication
Enter the number for multiplication table: 5
Multiplication table of 5 is :
Date:
5
10
15
20
25
30
35
40
45
50
*/
/*Write a program to calculate roots of quadratic equation*/
Practical No.:
import java.io.*;
class quadratic
{
public static void main(String[] args) throws IOException
{
int a,b,c,d;
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter the value of a =”);
a=Integer.parseInt(dr.readLine());
Date:
System.out.println(“Enter the value of b =”);
b=Integer.parseInt(dr.readLine());
System.out.println(“Enter the value of c =”);
c=Integer.parseInt(dr.readLine());
if(a==0)
{
if(b==0)
{
if(c==0) {System.out.println(“Root are …”+a+”and”+b);}
else {System.out.println(“Root does not exist …”);}
}
else {System.out.println(“Root is”+(-b/c));}
} else
{
d=b*b-(4*a*c);
if(d<0){System.out.println(“Root does not exist …”);}
else
{
if(d==0){System.out.println(“Root are …”+(-b/(2*a)));}
else
{
System.out.println(“Root are …”);
System.out.println(((-b+Math.sqrt(d))/(2*a)));
System.out.println(((-b-Math.sqrt(d))/(2*a)));
}
}}}}
/* Output:
H:\sem 4\Java\done>javac quadratic.java
H:\sem 4\Java\done>java quadratic
Enter the value of a = 1
Enter the value of b = 5
Enter the value of c = 5
Root are …
-1.381966011250105
-3.618033988749895 */
/*Write a program to create room class with attribute roomno, type, area & setdata and
displaydata Method*/
Practical No.:
import java.io.*;
class room
{
int rno,rarea;
String rtype;
boolean actype;
void setdata() throws IOException
{
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter Room Number”);
rno=Integer.parseInt(dr.readLine());
System.out.println(“Enter Room Type”);
rtype=dr.readLine();
System.out.println(“Enter Room Area”);
rarea=Integer.parseInt(dr.readLine());
Date:
System.out.println(“Is AC Room ? true/false”);
actype=Boolean.parseBoolean(dr.readLine());
}
void displaydata()
{
System.out.println(“Room Number=”+rno);
System.out.println(“Room Type=”+rtype);
System.out.println(“Room Area=”+rarea);
System.out.println(“AC Room =”+actype);
}
}
class roommain
{
public static void main(String[] args) throws IOException
{
room r=new room();
r.setdata();
r.displaydata();
}
}
/*
Output:
H:\sem 4\Java\done>javac roommain.java
H:\sem 4\Java\done>java roommain
Enter Room Number :10
Enter Room Type :2BHK
Enter Room Area :800
Is AC Room ? true/false :true
Room Number=10
Room Type=2BHK
Room Area=800
AC Room =true
*/
/* Develop bank account application with following transaction
i) deposit ii) withdraw iii) balance checking iv) display account holder details
Use constructor for initialize value.*/
Practical No.:
import java.io.*;
class bank
{
int accno;
Date:
String name;
int bal;
String acctype;
bank(int accno2,String name2,int bal2,String acctype2)
{
accno=accno2;
name=name2;
bal=bal2;
acctype=acctype2;
}
int balcheck() {return bal;}
void deposite(int amt)
{
bal=bal+amt;
System.out.println(“Deposit Transaction is Successfully(Current balance=”+bal+”)”);
}
void withdraw(int amt)
{
int cbal=balcheck();
if(cbal>=(amt+100))
{
bal=bal-amt;
System.out.println(“Withdraw Transaction is Successfully (Remaining balance=”+bal+”)”);}
else
{
System.out.println(“Withdraw Transaction is Failed due low balance in your account (current
balance=”+cbal+”)”);
}
}
void display()
{
System.out.println(“Account Number=”+accno);
System.out.println(“Customer Name=”+name);
System.out.println(“Balance=”+bal);
System.out.println(“Account Type =”+acctype);
}
}
class bankmain
{
public static void main(String[] args) throws IOException
{
int accno1=0;
String name1=””;
int bal1=0;
String acctype1=””;
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter Account Number”);
accno1=Integer.parseInt(dr.readLine());
System.out.println(“Enter Customer Name”);
name1=dr.readLine();
System.out.println(“Enter Starting Deposit Amount.”);
bal1=Integer.parseInt(dr.readLine());
System.out.println(“Enter Account Type”);
acctype1=dr.readLine();
bank r=new bank(accno1,name1,bal1,acctype1);
r.deposite(1000);
r.withdraw(1001);
System.out.println(“Current Balance in your account is “+r.balcheck());
r.display();
}
}
/*
Output:
H:\sem 4\Java\done>javac bankmain.java
H:\sem 4\Java\done>java bankmain
Enter Account Number 10002
Enter Customer Name Sam
Enter Starting Deposit Amount. 1000
Enter Account Type savings
Deposit Transaction is successfully (Current balance=2000)
Withdraw Transaction is successfully (Remaining balance=999)
Current Balance in your account is 999
Account Number = 10002
Customer Name = Sam
Balance = 999
Account Type = savings
*/
/*Write a program which contain method of cube such that
cube of 3 is a 27 and 0.2 is 0.008 */
Practical No.:
import java.io.*;
class cs
{
public int cube(int n1)
Date:
{return(n1*n1*n1);}
public float cube(float n1)
{return(n1*n1*n1);}
}
class cubeoverload
{
public static void main(String[] args)
{
cs c=new cs();
System.out.println(“Cube of 3 = “+c.cube(3));
System.out.println(“Cube of 0.2 = “+c.cube(0.2f));
}
}
/*
Output:
H:\sem 4\Java\done>javac cubeoverload.java
H:\sem 4\Java\done>java cubeoverload
Cube of 3 = 27
Cube of 0.2 = 0.008
*/
/*Write a program Set of overload methods power that returns x^n where n is Int and x
may be Int or Float.*/
Practical No.:
import java.io.*;
class cs
{
public double power(int x,int n)
{return(Math.pow(x,n));}
public double power(double x,int n)
{return(Math.pow(x,n));}
}
class poweroverload
{
public static void main(String[] args)
{
cs c=new cs();
System.out.println(“Power of 4=”+c.power(4,4));
System.out.println(“Power of 0.2=”+(float)c.power(0.2,4));
}
}
/*
Date:
Output:
H:\sem 4\Java\done>javac poweroverload.java
H:\sem 4\Java\done>java poweroverload
Power of 4=256.0
Power of 0.2=0.0016
*/
/*Write a program to define class a student which takes value for name regno, marks of
three subject & overload the constructor, copy constructor & the objects*/
Practical No.:
import java.io.*;
class student
{
String name;
int regno;
int m1,m2,m3;
student()
{
name=”Santosh”;
regno=10;
m1=89; m2=60; m3=70;
Date:
}
student(String name1,int regno1,int m11,int m22,int m33)
{
name=name1;
regno=regno1;
m1=m11; m2=m22; m3=m33;
}
student(student s)
{
name=s.name;
regno=s.regno;
m1=s.m1; m2=s.m2; m3=s.m3;
}
public void display()
{
System.out.println(“\nStudent Details are :”);
System.out.println(“Name = “+name);
System.out.println(“Reg No = “+regno);
System.out.println(“M1 = “+m1+”, M2 = “+m2+”, M3 = “+m3);
}
}
class studentoverload
{
public static void main(String[] args)
{
student s1=new student();
s1.display();
student s2=new student(“Sunil”,20,100,89,60);
s2.display();
student s3=new student(s2);
s3.display();
}
}
/*
Output:
H:\sem 4\Java\done>javac studentoverload.java
H:\sem 4\Java\done>java studentoverload
Student Details are :
Name = Santosh
Reg No = 10
M1 = 89, M2 = 60, M3 = 70
Student Details are :
Name = Sunil
Reg No = 20
M1 = 100, M2 = 89, M3 = 60
Student Details are :
Name = Sunil
Reg No = 20
M1 = 100, M2 = 89, M3 = 60
*/
/* Create object of test class and pass the object to another class*/
Practical No.:
import java.io.*;
class test
{
private int a,b;
test (int i,int j){a=i;b=j;}
public boolean equals(test o)
{
if(o.a==a && o.b==b)
return true;
else
return false;
}
}
Date:
class result
{
public static void main(String[] args)
{
test o1=new test(10,20);
test o2=new test(10,20);
test o3=new test(100,200);
System.out.println(“O1 == O2 is “+o1.equals(o2));
System.out.println(“O1 == O3 is “+o1.equals(o3));
}
}
/*
Output:
H:\sem 4\Java\done>javac result.java
H:\sem 4\Java\done>java result
O1 == O2 is true
O1 == O3 is false
*/
/*Create employee class with attributes empid, name, basic salary, implement or
overload toString method of employee class to represent a string presentation of an
employee object. The method should return empid, name & Salary of employee*/
Practical No.:
Date:
import java.io.*;
class employee
{
int empno;
String name;
double sal;
employee(int no, String n,double s)
{
empno=no;
name=n;
sal=s;
}
public String toString()
{
return(empno+name+sal);
}
}
class emptoString
{
public static void main(String[] args)
{
employee o1=new employee(10,”Santosh”,10000);
System.out.println(“EmpToString Method Output : “+o1.toString());
}
}
/*
Output:
H:\sem 4\Java\done>javac emptoString.java
H:\sem 4\Java\done>java emptoString
EmpToString Method Output : 10Santosh10000.0
*/
/*create employee class with attributes eid, name, sal and
display no of employee using static method total_employee.
Modify the employee class to implement auto generation of eid*/
Practical No.:
import java.io.*;
class employee
{
static int i=0;
int empno;
String name;
double sal;
Date:
employee(){}
employee(String n,double s)
{
i=i+1;
empno=1000+i;
name=n;
sal=s;
}
public void display()
{
System.out.print(” Employee id is “+empno);
System.out.print(” Employee name is “+name);
System.out.println(” Employee sal is “+sal);
}
public static void totalemp()
{
System.out.println(“Total employee are :”+i);
}
}
class staticemp
{
public static void main(String[] args)
{
employee o=new employee();
o.totalemp();
employee o1=new employee(“Sameer”,10000);
employee o2=new employee(“Prasad”,20000);
o.totalemp();
employee o3=new employee(“Nayan”,30000);
employee o4=new employee(“Tanmay”,40000);
o.totalemp();
o1.display();
o2.display();
o3.display();
o4.display();
}
}
/*
Output:
H:\sem 4\Java\done>javac staticemp.java
H:\sem 4\Java\done>java staticemp
Total employee are :0
Total employee are :2
Total employee are :4
Employee id is 1001 Employee name is Sameer Employee sal is 10000.0
Employee id is 1002 Employee name is Prasad Employee sal is 20000.0
Employee id is 1003 Employee name is Nayan Employee sal is 30000.0
Employee id is 1004 Employee name is Tanmay Employee sal is 40000.0
*/
/*Create a class rectangle which will overload the constructor
and display area of rectangle*/
Practical No.:
import java.io.*;
class rectangle
{
private int l,b;
rectangle ()
{l=0;b=0;}
rectangle (int i,int j)
{l=i;b=j;}
rectangle (rectangle r)
{l=r.l;b=r.b;}
public double area()
Date:
{return(l*b);}
}
class rect_area
{
public static void main(String[] args)
{
rectangle o1=new rectangle();
rectangle o2=new rectangle(10,20);
rectangle o3=new rectangle(o2);
System.out.println(“Area of Rectangle1 =”+o1.area());
System.out.println(“Area of Rectangle2 =”+o2.area());
System.out.println(“Area of Rectangle3 =”+o3.area());
}}
/*
Output:
H:\sem 4\Java\done>javac rect_area.java
H:\sem 4\Java\done>java rect_area
Area of Rectangle1 =0.0
Area of Rectangle2 =200.0
Area of Rectangle3 =200.0
*/
/* Write a program to demonstrate Interface */
Practical No.:
interface area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{return(x*y);}
}
class circle implements area
{
public float compute(float x,float y)
{return(2*pi*x*y);}
}
class interfaces
{
public static void main(String args[])
{
rectangle r=new rectangle();
Date:
circle c=new circle();
System.out.println(“Area of Rectangle is = “+r.compute(10.00F,20.00F));
System.out.println(“Area of Circle is = “+c.compute(10.00F,10.00F));
}
}
/*
Output:
H:\sem 4\Java\done>javac interfaces.java
H:\sem 4\Java\done>java interfaces
Area of Rectangle is = 200.0
Area of Circle is = 628.0
*/
/* Write a program to demonstrate Hierarchical inheritance and method overriding*/
Practical No.:
class Rodent
{
void eat(){}
}
class Mouse extends Rodent
Date:
{
public void eat()
{System.out.println(“Mouse is eating ….. “);}
}
class Gerbil extends Rodent
{
public void eat()
{System.out.println(“Gerbil is eating ….. “);}
}
class Hamster extends Rodent
{
public void eat()
{System.out.println(“Hamster is eating ….. “);}
}
class overrides
{
public static void main(String args[])
{
Rodent r[]=new Rodent[3];
r[0]= new Mouse();
r[1]= new Gerbil();
r[2]= new Hamster();
r[0].eat();
r[1].eat();
r[2].eat();
} }
/*
Output:
H:\sem 4\Java\done>javac overrides.java
H:\sem 4\Java\done>java overrides
Mouse is eating …..
Gerbil is eating …..
Hamster is eating …..
*/
/* Write a program to demonstrate Student interface*/
Practical No.:
import java.io.*;
interface student
{
void display_grade();
void display_attend();
}
class all_student
{
String name,grade;
int reg,attend,m1,m2,m3,total;
all_student() throws IOException
Date:
{
DataInputStream dr = new DataInputStream(System.in);
System.out.println(“Enter Student Reg. Number”);
reg=Integer.parseInt(dr.readLine());
System.out.println(“Enter Student Name”);
name=dr.readLine();
System.out.println(“Enter Student Attendance”);
attend=Integer.parseInt(dr.readLine());
System.out.println(“Enter 3 Subject Marks”);
m1=Integer.parseInt(dr.readLine());
m2=Integer.parseInt(dr.readLine());
m3=Integer.parseInt(dr.readLine());
total=m1+m2+m3;
if(total>=250)
grade=”A”;
else if(total>=200)
grade=”B”;
else if(total>=150)
grade=”C”;
else if(total>=100)
grade=”D”;
else
grade=”E”;
}}
class pg_student extends all_student implements student
{
pg_student() throws IOException
{
super();
}
public void display_grade()
{
System.out.println(“Post Graduate Student Details “);
System.out.println(“Student Reg. Number is “+reg);
System.out.println(“Student Name is “+name);
System.out.println(“Student 3 Subject Marks are “+m1+” , “+m2+”, “+m3);
System.out.println(“Student Total Marks is “+total);
System.out.println(“Student Grade is “+grade);
}
public void display_attend()
{
System.out.println(“Student Attendance is”+attend);
}
}
class ug_student extends all_student implements student
{
ug_student() throws IOException
{
super();
}
public void display_grade()
{
System.out.println(“Under Graduate Student Details “);
System.out.println(“Student Reg. Number is “+reg);
System.out.println(“Student Name is “+name);
System.out.println(“Student 3 Subject Marks are “+m1+” , “+m2+”, “+m3);
System.out.println(“Student Total Marks is “+total);
System.out.println(“Student Grade is “+grade);
}
public void display_attend()
{
System.out.println(“Student Attendance is”+attend);
}
}
class studentinterface
{
public static void main(String args[]) throws IOException
{
System.out.println(“Enter Post Graduate Student Details “);
pg_student pg=new pg_student();
pg.display_grade();
pg.display_attend();
System.out.println(“Enter Under Graduate Student Details “);
ug_student ug=new ug_student();
ug.display_grade();
ug.display_attend();
}
}
/*
Output:
H:\sem 4\Java\done>javac studentinterface.java
H:\sem 4\Java\done>java studentinterface
Enter Post Graduate Student Details
Enter Student Reg. Number 17
Enter Student Name Raj
Enter Student Attendance 95
Enter 3 Subject Marks 10 10 10
Post Graduate Student Details
Student Reg. Number is 17
Student Name is Raj
Student 3 Subject Marks are 10 , 10, 10
Student Total Marks is 30
Student Grade is E
Student Attendance is95
Enter Under Graduate Student Details
Enter Student Reg. Number 13
Enter Student Name Sameer
Enter Student Attendance 75
Enter 3 Subject Marks 10 9 8
Under Graduate Student Details
Student Reg. Number is 13
Student Name is Sameer
Student 3 Subject Marks are 10 , 9, 8
Student Total Marks is 27
Student Grade is E
Student Attendance is75
*/
/* Write a program to implements all the java Wrapper classes. */
Practical No.:
import java.io.*;
class typecast {
double num1;
DataInputStream ds;
public typecast()
{ds=new DataInputStream(System.in);}
Date:
public void getData(){
System.out.println(“Enter Values for Double: “);
try{num1=Double.parseDouble(ds.readLine());}
catch(Exception e){
System.out.println(e);}}
public void convertDoubleToInt()
{System.out.println(“Double to Integer : “+(int)num1);}
public void convertDoubleToByte()
{System.out.println(“Double to Byte : “+(byte)num1);}
}
public class Wrapper{
public static void main(String[] args)
{
typecast c=new typecast();
c.getData();
c.convertDoubleToInt();
c.convertDoubleToByte();
}
}
/*
Output:
H:\sem 4\Java\done>javac Wrapper.java
H:\sem 4\Java\done>java Wrapper
Enter Values for Double : 10.6
Double to Integer : 10
Double to Byte : 10
*/
/*Write a program to perform various operation on string*/
Practical No.:
class Strings
{
public static void main(String[] args)
{
String str=”Bharti Vidyapeeth!”;
String st=”a”;
System.out.println(” Lower case “+str.toLowerCase());
System.out.println(” Upper case “+str.toUpperCase());
System.out.println(” Char At “+str.charAt(2));
System.out.println(” Ends With ! “+str.endsWith(“!”));
System.out.println(” Index of ! “+str.indexOf(“!”));
System.out.println(” Replacement “+st.replace(st, str));
System.out.println(” Last Index of ! “+str.lastIndexOf(“e”));
}
}
Date:
/*
Output:
H:\sem 4\Java\done>javac Strings.java
H:\sem 4\Java\done>java Strings
Lower case bharti vidyapeeth!
Upper case BHARTI VIDYAPEETH!
Char At a
Ends With ! true
Index of ! 17
Replacement Bharti Vidyapeeth!
Last Index of ! 14
*/
/*Write a program in java for Runtime polymorphism */
Practical No.:
class figure
{
double d1,d2;
double area(){return 0.0;}
}
class rectangle extends figure
Date:
{
double area(double a,double b)
{
return(a*b);
}
}
class triangle extends figure
{
double area(double a,double b)
{
return((0.5)*a*b);
}
}
class runpoly
{
public static void main(String args[])
{
figure f=new figure();
rectangle r=new rectangle();
triangle t=new triangle();
System.out.println(“Area of Figure=>”+r.area());
System.out.println(“Area of Rectangle=>”+r.area(10.0,20.0));
System.out.println(“Area of Triangle=>”+t.area(10.0,20.0));
}
}
/*
Output:
H:\sem 4\Java\done>javac runpoly.java
H:\sem 4\Java\done>java runpoly
Area of Figure=>0.0
Area of Rectangle=>200.0
Area of Triangle=>100.0
*/
/* Write a program to demonstrate simple package – balance, accountbalance*/
Practical No.:
package MyPack;
class AccountBalance
{
int acc_id;
String ac_name;
float Balance;
public AccountBalance(int acc_id1,String ac_name1,float Balance1)
{
acc_id=acc_id1;
ac_name=ac_name1;
Balance=Balance1;
Date:
}
public void show()
{
System.out.println(“\n id “+acc_id+”\n name”+ac_name+”\n balance “+Balance);
}
}
class Account
{
public static void main(String[] args)
{
AccountBalance a=new AccountBalance(10,”santosh”,12000);
a.show();
}
}
/*
Output:
H:\sem 4\Java\done>javac Account.java
H:\sem 4\Java\done>java Account
id 10
name Eric
balance 12000
*/
/*write a program which will create user defined packages for Maharashtra, Andhra
Pradesh, Uttar Pradesh. Create sub-packages Mumbai, Pune in Maharashtra which
will have CST station, SarasBaug as classes. Create sub-package Agra in Uttar Pradesh
which will have a class Tajmahal. In Andhra Pradesh create class as Charminar.*/
Practical No.:
Date:
import AndhraPradesh.charminar;
import maharashtra.mumbai.*;
import maharashtra.pune.*;
import uttarpradesh.agra.tajmahal;
public class India {
public static void main(String[] args) {
charminar c=new charminar();
mumbai m=new mumbai();
pune p=new pune();
tajmahal t=new tajmahal();
}
}
package AndhraPradesh;
public class charminar {
public charminar()
{
System.out.println(“AANDHRAPRADESH: CHARMINAR IN INDIA PACKAGE”);
}
}
package maharashtra.mumbai;
public class mumbai {
public mumbai()
{
System.out.println(“MUMBAI : GATEWAY OF INDIA”);
}
}
package maharashtra.pune;
public class pune {
public pune()
{
System.out.println(“PUNE:SARASBAG IN MAHARASHTRA PACKAGE “);
}
}
package uttarpradesh.agra;
public class tajmahal {
public tajmahal()
{
System.out.println(“TAJMAHAL IN UTTARPRADESH”);
}
}
/*
Output:
H:\sem 4\Java\done>javac India.java
H:\sem 4\Java\done>java India
AANDHRAPRADESH: CHARMINAR IN INDIA PACKAGE
MUMBAI : GATEWAY OF INDIA
PUNE:SARASBAG IN MAHARASHTRA PACKAGE
TAJMAHAL IN UTTARPRADESH
*/
/* Write a program to demonstrate Simple JDBC Connection*/
Practical No.:
import java.sql.*;
import java.io.*;
public class db {
public static void main(String arg[])
{
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:testx”,””,””);
Statement st=con.createStatement();
Date:
ResultSet rs=st.executeQuery(“select * from emp”);
System.out.println(“Connection done Sucessfully…”);
System.out.println(“Employee Names…”);
while(rs.next())
{
System.out.println(rs.getString(1));
}
con.close();
}
catch (Exception e)
{System.out.println(e);}
}
}
/*
Output:
H:\sem 4\Java\done>javac db.java
H:\sem 4\Java\done>java db
Connection done Sucessfully…
Employee Names…
sameer
sai
sunil
*/
/*Write a program to create Traffic signal using Applet.*/
Practical No.:
import java.awt.Graphics;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
/*
<applet code=”Traffic.class” width=”150″ height=”200″> </applet>
*/
public class Traffic extends Applet
{
Button b2;
public Traffic()
{
b2=new Button(“Traffic Signal.”);
add(b2);
}
public boolean action(Event e,Object o)
{
if(e.target==b2)
{
Graphics g=getGraphics();
Date:
g.drawRect(20,35,40,90);
g.setColor (Color.black);
g.setColor(Color.red );
g.fillOval (30, 40, 20, 20);
g.setColor(Color.yellow);
g.fillOval (30, 70, 20, 20);
g.setColor(Color.green);
g.fillOval (30, 100, 20, 20);
}
return(true);
}
}
/*
Output:
H:\sem 4\Java\done>javac Traffic.java
H:\sem 4\Java\done>appletviewer Traffic.java
*/
/*Write a program to create India Flag using Applet.*/
Practical No.:
import java.awt.Graphics;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
/*
<applet code=”Flag.class” width=”300″ height=”500″> </applet>
*/
public class Flag extends Applet
{
public void paint(Graphics g)
{
g.fillOval(60,450,120,50);
g.drawString(“I Love My India”,140,60);
g.fillRect(110,60,10,400);
g.setColor(Color.red);
g.fillRect(120,80,150,30);
g.setColor(Color.white);
g.fillRect(120,110,150,30);
g.setColor(Color.green);
g.fillRect(120,140,150,30);
g.setColor(Color.black);
g.drawRect(120,80,150,90);
Date:
g.setColor(Color.blue);
g.drawOval(180,110,30,30);
int t=0;
int x=195,y=125;
double x1,y1, d;
double r=15;
for(int i=1;i<=24;i++)
{
d=(double)t*3.14/180.0;
x1=x+(double)r*Math.cos(d);
y1=y+(double)r*Math.sin(d);
g.drawLine(x,y,(int)x1,(int)y1);
t+=360/24;
}
}
}
/*
Output:
H:\sem 4\Java\done>javac Flag.java
H:\sem 4\Java\done>appletviewer Flag.java
*/
/*Write a program to create Ashok Chakra using Applet.*/
Practical No.:
import java.awt.Graphics;
import java.awt.*;
import javax.swing.*;
import java.applet.*;
/* <applet code=”Chakra.class” width=”350″ height=”200″> </applet> */
public class Chakra extends Applet
{
public void paint(Graphics g)
{
g.drawString(“ASHOK CHAKRA”,140,10);
g.setColor(Color.blue);
g.drawOval(105,35,150,150);
int x=180,y=110, t=0;
double x1,y1, d;
double r=75;
for(int i=1;i<=24;i++)
{
d=(double)t*3.14/180.0;
x1=x+(double)r*Math.cos(d);
y1=y+(double)r*Math.sin(d);
Date:
g.drawLine(x,y,(int)x1,(int)y1);
t+=360/24;
}
}
}
/*
Output:
H:\sem 4\Java\done>javac Chakra.java
H:\sem 4\Java\done>appletviewer Chakra.java
*/
/*Write a program which will have an applet. Create a string which will scroll from left
to right on screen*/
Practical No.:
Date:
import java.awt.*;
import java.applet.*;
/*<applet code=”simplebanner.class” width=”350″ height=”200″> </applet>*/
public class simplebanner extends Applet implements Runnable
{
String txt=” Santosh Goilkar
Thread t=null;
boolean stopflag;
@Override
“;
public void init()
{ setForeground(Color.red); }
@Override
public void start()
{ t = new Thread(this);
stopflag=false;
t.start(); }
public void run()
{ char ch;
for(;;)
{
try{
repaint();
Thread.sleep(650);
ch=txt.charAt(0);
txt=txt.substring(1,txt.length());
txt=txt+ch;
if(stopflag)
break;
}catch(InterruptedException e) {}
}
}
@Override
public void stop()
{ stopflag=true;
t=null; }
@Override
public void paint(Graphics g)
{
g.drawString(txt,100,80);
showStatus(“Simple Banner”);
}
}
/*
Output:
H:\sem 4\Java\done>javac simplebanner.java
H:\sem 4\Java\done>appletviewer simplebanner.java
*/
/* Write a program to demonstrate Package
with Mypack- Circle,Rectangle,Triangle with area() */
Practical No.:
Date:
package mypack;
public class circle {
public circle(int r)
{
System.out.println(“area of circle” +3.14*r*r);
}
}
package mypack;
public class rectangle {
public rectangle(int l,int w)
{
System.out.println(“area of rectangle =” +l*w); }
}
package mypack;
public class triangle {
public triangle(int b,int h)
{
System.out.println(“area of rectangle=” +0.5*b*h); }
}
import mypack.*;
public class cir_pack {
public static void main(String[] args) {
circle c=new circle(15);
rectangle r=new rectangle(15,17);
triangle t=new triangle(13,17);
}
}
/*
Output:
H:\sem 4\Java\done>cd mypack
H:\sem 4\Java\done\mypack>javac circle.java
H:\sem 4\Java\done\mypack>javac rectangle.java
H:\sem 4\Java\done\mypack>javac triangle.java
H:\sem 4\Java\done\mypack>cd ..
H:\sem 4\Java\done>javac cir_pack.java
H:\sem 4\Java\done>java cir_pack
area of circle =706.5
area of rectangle =255
area of triangle =110.5
*/
/*Write a program to demonstrate a normal thread.*/
Practical No.:
class ThreadDemo
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread”+t);
Date:
t.setName(“My Thread”);
System.out.println(“After name change”+t);
try
{
for(int n=5;n>0;n–)
{
System.out.println(n);
Thread.sleep(100);
}
}
catch(InterruptedException e)
{ System.out.println(“Main Thraed”); }
}
}
/*
Output:
H:\sem 4\Java\done>javac ThreadDemo.java
H:\sem 4\Java\done>java ThreadDemo
Current ThreadThread[main,5,main]
After name changeThread[My Thread,5,main]
5
4
3
2
1
*/
/*create an applet which will have a bouncing ball using thread.
perform bouncing action onclick of start and stop button*/
Practical No.:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class BounceThreadExample
{
public static void main(String[] args)
{
JFrame frame = new BounceThread();
frame.show();
}
}
class BounceThread extends JFrame
{
private JPanel canvas;
Date:
public BounceThread()
{
setSize(300, 200);
setTitle(“Bounce Ball”);
Container container = getContentPane();
canvas = new JPanel();
container.add(canvas, “Center”);
JPanel panel = new JPanel();
add(panel, “Start”, new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
Ball ball = new Ball(canvas);
ball.start();
}
});
add(panel, “Stop”, new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
canvas.setVisible(false);
System.exit(0);
}
});
container.add(panel, “North”);
}
public void add(Container container, String title, ActionListener listener)
{
JRadioButton button = new JRadioButton(title);
container.add(button);
button.addActionListener(listener);
}
}
class Ball extends Thread
{
JPanel box;
int P = 12, Q = 12, p = 0, q = 0, dp = 3, dq = 3;
public Ball(JPanel pan)
{ box = pan;
}
public void draw()
{
Graphics g = box.getGraphics();
g.fillOval(p, q, P, Q);
g.dispose();
}
public void move()
{
if (!box.isVisible())
return;
Graphics g = box.getGraphics();
g.setXORMode(box.getBackground());
g.fillOval(p, q, P, Q);
p += dp;
q += dq;
Dimension d = box.getSize();
if (p < 0)
{
p = 0;
dp = -dp;
}
if (p + P >= d.width)
{
p = d.width – P;
dp = -dp;
}
if (q < 0)
{
q = 0;
dq = -dq;
}
if (q + Q >= d.height)
{
q = d.height – Q;
dq = -dq;
}
g.fillOval(p, q, P, Q);
g.dispose();
}
public void run()
{
try
{ draw();
while (true)
{
move();
sleep(5);
}
} catch (Exception e) { }
}
}
/*
Output:
H:\sem 4\Java\done>javac BounceThreadExample.java
H:\sem 4\Java\done>java BounceThreadExample
*/
/*Write a program that implements a simple form of
the Producer Consumer problem.*/
Practical No.:
import java.io.*;
public class ProducerConsumerTest
{
public static void main(String[] args)
{
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole
{
private int contents;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try
Date:
{
wait(); }
catch (InterruptedException e){}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{ wait();}
catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}}
class Consumer extends Thread
{
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number)
{
cubbyhole = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = cubbyhole.get();
System.out.println(“Consumer #”+ this.number+ ” got: ” + value);
}
}
}
class Producer extends Thread
{
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number)
{
cubbyhole = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
cubbyhole.put(i);
System.out.println(“Producer #” + this.number+ ” put: ” + i);
try
{ sleep((int)(Math.random() * 100));}
catch (InterruptedException e) { }
}
}
}
/*
Output:
H:\sem 4\Java\done>javac ProducerConsumerTest.java
H:\sem 4\Java\done>java ProducerConsumerTest
Producer #1 put: 0
Consumer #1 got: 0
Consumer #1 got: 1
Producer #1 put: 1
Consumer #1 got: 2
Producer #1 put: 2
Consumer #1 got: 3
Producer #1 put: 3
Consumer #1 got: 4
Producer #1 put: 4
Consumer #1 got: 5
Producer #1 put: 5
Consumer #1 got: 6
Producer #1 put: 6
Consumer #1 got: 7
Producer #1 put: 7
Consumer #1 got: 8
Producer #1 put: 8
Consumer #1 got: 9
Producer #1 put: 9
*/
/*Write a program to demonstrate Serializable files – Employee, Serializableclass,
DesrializableClass.*/
Practical No.:
// Employee.java
class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
Date:
public void mailCheck()
{
System.out.println(“Mailing a check to ” + name + ” ” + address); }
}
//SerializeDemo.java
import java.io.*;
class SerializeDemo
{
public static void main(String[] args)
{
Employee e = new Employee();
e.name = “Sameer Deshmukh”;
e.address = “Chembur”;
e.SSN = 10;
e.number = 1010;
try
{
FileOutputStream fileOut = new FileOutputStream(“employee.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println(“serealized”);
}
catch (IOException i) { i.printStackTrace(); }
}
}
// DeserializeDemo.java
import java.io.*;
class DeserializeDemo
{
public static void main(String[] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream(“employee.ser”);
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}
catch (IOException i)
{
i.printStackTrace();
return;
} catch (ClassNotFoundException c)
{
System.out.println(“Employee class not found”);
c.printStackTrace();
return;
}
System.out.println(“Name: ” + e.name);
System.out.println(“Address: ” + e.address);
System.out.println(“SSN: ” + e.SSN);
System.out.println(“Number: ” + e.number);
}
}
/*
Output:
H:\sem 4\Java\done>javac Employee.java
H:\sem 4\Java\done>javac SerializeDemo.java
H:\sem 4\Java\done>java SerializeDemo
serealized
H:\sem 4\Java\done>javac DeserializeDemo.java
H:\sem 4\Java\done>java DeserializeDemo
Name: Sameer Deshmukh
Address: Chembur
SSN: 10
Number: 1010
*/
/*Write a program to demonstrate the working of synchronized ()
in Banking domain to manage Deposit and withdraw operations smoothly */
Practical No.:
class DepositeThread implements Runnable
{
private Account account ;
private double amount;
public DepositeThread(Account account,double amount)
{
this.account=account;
this.amount=amount;
}
public void run ()
{account.deposit(amount);}
}
class WithdrawThread implements Runnable
{
private Account account ;
private double amount;
public WithdrawThread(Account account,double amount)
{
this.account=account;
this.amount=amount;
Date:
}
public void run ()
{ account.withdraw(amount); }
}
class Account
{
private double balance=0;
public Account (double balance)
{ this.balance=balance; }
synchronized public void deposit(double amount)
{
if (amount <0)
{ throw new IllegalArgumentException(“Cant deposit”); }
this.balance+=amount;
System.out.println(“Deposit ” +amount+” in thread”+Thread.currentThread().getId()+”,
balance is ” +balance);
}
synchronized public void withdraw(double amount)
{
if (amount<0 || amount>this.balance)
{ throw new IllegalArgumentException(“cant withdraw”); }
this.balance-=amount;
System.out.println(“withdraw “+amount+” in thread”+Thread.currentThread().getId()+”,
balance is ” +balance);
}
}
public class InternetBankingSystem
{
public static void main (String args[])
{
Account accountObject =new Account (100);
new Thread (new DepositeThread(accountObject,30)).start();
new Thread (new DepositeThread(accountObject,20)).start();
new Thread (new DepositeThread(accountObject,10)).start();
new Thread (new WithdrawThread(accountObject,30)).start();
new Thread (new WithdrawThread(accountObject,50)).start();
new Thread (new WithdrawThread(accountObject,20)).start();
}
}
/*
Output:
H:\sem 4\Java\done>javac InternetBankingSystem.java
H:\sem 4\Java\done>java InternetBankingSystem
Deposit 30.0 in thread8, balance is 130.0
Deposit 20.0 in thread9, balance is 150.0
Deposit 10.0 in thread10, balance is 160.0
withdraw 30.0 in thread11, balance is 130.0
withdraw 50.0 in thread12, balance is 80.0
withdraw 20.0 in thread13, balance is 60.0
*/
/* Write a program which will read and write content of file
using FileReader,FileWriter */
Practical No.:
import java.io.*;
public class CopyFileReader {
public static void main(String[] args) {
File File1 = new File(“E:\\File1.txt”);
File File2 = new File(“E:\\File2.txt”);
FileReader in = null;
FileWriter out = null;
try{
in = new FileReader(File1);
out = new FileWriter(File2);
int ch;
Date:
while((ch=in.read())!=-1)
{
System.out.print((char)ch);
out.write(ch);
}
System.out.println(“\nFile1 content is copied to File2 Successfully… “);
out.close();
in.close();
}catch(Exception e){}
}
}
/*
Output:
H:\sem 4\Java\done>javac CopyFileReader.java
H:\sem 4\Java\done>java CopyFileReader
Bharti Vidyapeeth !!!!
File1 content is copied to File2 Successfully…
*/
/*Write a program which will Concat 2 file */
Practical No.:
Date:
import java.io.*;
class SequenceBuffer
{
public static void main(String args[]) throws IOException
{
FileInputStream file1=null;
FileInputStream file2=null;
SequenceInputStream file3=null;
file1= new FileInputStream(“E:\\File1.txt”);
file2= new FileInputStream(“E:\\File2.txt”);
file3=new SequenceInputStream(file1,file2);
BufferedInputStream inBuffer= new BufferedInputStream(file3);
BufferedOutputStream outBuffer= new BufferedOutputStream(System.out);
int ch;
while((ch=inBuffer.read())!=-1)
{
outBuffer.write((char)ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
/*
Output:
H:\sem 4\Java\done>javac SequenceBuffer.java
H:\sem 4\Java\done>java SequenceBuffer
Bharti Vidyapeeth !!!! */
/* Write a program which will Takes data from fileinputstream
and copy it into fileoutputstream.*/
Practical No.:
import java.io.*;
class CopyFileInputStream
{
public static void main(String[] args)
{
try
{
FileInputStream fin = new FileInputStream(“E:\\File1.txt”);
FileOutputStream fout = new FileOutputStream(“E:\\File3.txt”);
int i=0;
while(i!=-1)
{
Date:
i = fin.read();
fout.write(i);
System.out.print ((char)i);
}
System.out.println (“\nFile1 content is copied at File3 SucessFully… “);
fin.close();
fout.close();
}
catch(IOException e){}
}
}
/*
Output:
H:\sem 4\Java\done>javac CopyFileInputStream.java
H:\sem 4\Java\done>java CopyFileInputStream
Bharti
File1 content is copied at File3 SucessFully…
*/
/* Write a program which will Takes data from byte array and write to file.*/
Practical No.:
Date:
import java.io.*;
class WriteByteArray
{
public static void main(String[] args)
{
try
{
byte b[]={‘B’,’H’,’A’,’R’,’A’,’T’,’I’};
FileOutputStream out=new FileOutputStream(“E:\\File1.txt”);
System.out.println (“\nByte array is copied at File1 successfully… “);
out.write(b);
out.close();
}
catch(IOException e){ }
}
}
/*
Output:
H:\sem 4\Java\done>javac WriteByteArray.java
H:\sem 4\Java\done>java WriteByteArray
Byte array is copied at File1 successfully…*/
/*Write a program which will create threads with different t priority */
Practical No.:
class thrun implements Runnable
{
Thread t;
boolean runn = true;
thrun(String st,int p)
{
t = new Thread(this,st);
t.setPriority(p);
t.start();
}
public void run()
{
System.out.println(“Thread name : ” + t.getName());
System.out.println(“Thread Priority : ” + t.getPriority());
}
}
class priority{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
thrun t1 = new thrun(“Thread1″,Thread.NORM_PRIORITY + 2);
Date:
thrun t2 = new thrun(“Thread2″,Thread.NORM_PRIORITY – 2);
System.out.println(“Main Thread : ” + Thread.currentThread());
System.out.println(“Main Thread Priority : ” + Thread.currentThread().getPriority());
}
}
/*
Output:
H:\sem 4\Java\done>javac priority.java
H:\sem 4\Java\done>java priority
Main Thread : Thread[main,10,main]
Main Thread Priority : 10
Thread name : Thread1
Thread Priority : 7
Thread name : Thread2
Thread Priority : 3
*/
/* Write a program to demonstrate Use of all class of jdbc */
Practical No.:
import java.sql.*;
import java.io.*;
Date:
class jdbc_class
{
public static void main(String arg[])
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:testx”,””,””);
Statement smt=con.createStatement();
ResultSet res=smt.executeQuery(“Select * from emp where dept=’IT’ “);
int sum=0,temp=0;
System.out.println(“***Record for IT Department ***”);
while(res.next())
{
System.out.println(“Emp. Name is ” +res.getString(“name”));
temp=res.getInt(“salary”);
System.out.println(“Emp. Salary is ” +temp);
sum=sum+temp;
}
System.out.println(“Total Salary of emp in IT department ” +sum);
}
catch (java.lang.Exception ex)
{
System.out.println(“Error in connection”);
ex.printStackTrace();
}
}
}
/*
Output:
H:\sem 4\Java\done>javac jdbc_class.java
H:\sem 4\Java\done>java jdbc_class
***Record for IT Department ***
Emp. Name is Raj
Emp. Salary is 300
Emp. Name is Tejas
Emp. Salary is 200
Total Salary of emp in IT department 500
*/
/* Write a program to store telephone directory
implement all operation using jdbc*/
Practical No.:
import java.sql.*;
import java.io.*;
class action
{String url,qs;
Connection con;
Statement smt;
Date:
void conn_close()
{
try{
smt.close();
con.close();
}catch (java.lang.Exception ex){System.out.println(“Error in connection”);}
}
void connect()
{
try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=DriverManager.getConnection(“jdbc:odbc:testx”,””,””);
smt=con.createStatement();
}catch (java.lang.Exception ex){System.out.println(“Error in
connection”);ex.printStackTrace();}
}
void insert(String name,String number)
{
try{
connect();
qs=”insert into contact values(‘”+name+”‘,’”+number+”‘)”;
smt.executeUpdate(qs);
System.out.println(“Record Inserted..”);
conn_close();
}catch (Exception ex){System.out.println(“Error in connection”);ex.printStackTrace();}
}
void update(String name,String number)
{
try{
connect();
qs=”update contact set Phone=’”+number+”‘ where Name=’”+name+”‘”;
smt.executeUpdate(qs);
System.out.println(“Record Updated..”);
conn_close();
}catch (java.lang.Exception ex){System.out.println(“Error in connection
UPDATE”);ex.printStackTrace();}
}
void delete(String name)
{
try{
connect();
qs=”delete from contact where Name=’”+name+”‘”;
smt.executeUpdate(qs);
System.out.println(“Record deleted..”);
conn_close();
}catch (java.lang.Exception ex){System.out.println(“Error in connection
UPDATE”);ex.printStackTrace();}
}
void display(String name)
{
try{
connect();
qs=”select * from contact where Name like ‘%”+name+”%’”;
ResultSet rs = smt.executeQuery(qs);
while(rs.next())
{
System.out.println(“Contact no for “+rs.getString(“Name”)+” is “+rs.getString(“Phone”));
}
rs.close();
conn_close();
}catch (Exception ex){System.out.println(“Error in connection
UPDATE”);ex.printStackTrace();}
}}
class Directory
{
public static void main(String args[]) throws IOException
{
action a=new action();
DataInputStream in=new DataInputStream(System.in);
int c,count;
char choice;
String name,number;
do
{
try{
System.out.println(“\t Select Operation \n”);
System.out.println(“\t1. Add Contact”);
System.out.println(“\t2. Search Contact”);
System.out.println(“\t3. Delete Contact”);
System.out.println(“\t4. Updtae Contact”);
System.out.println(“\n\t Enter your choice:- “);
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1 :
System.out.println(” \t How many contact you want to add in database: “);
count=Integer.parseInt(in.readLine());
for(int i=0;i<count;i++)
{
System.out.println(” \t Enter data the Name and Phone: “);
name=in.readLine();
number=in.readLine();
a.insert(name,number);
}
break;
case 2 :
System.out.println(” \t Enter Name of student for contact Search: “);
name=in.readLine();
a.display(name);
break;
case 3 :
System.out.println(” \t Enter Name of student to delete from database : “);
name=in.readLine();
a.delete(name);
break;
case 4 :
System.out.println(” \t Enter data the Name and Phone for update: “);
name=in.readLine();
number=in.readLine();
a.update(name,number);
break;
default :
System.out.println(“\n Enter right choice :”);
break;
}
}catch(Exception e){e.printStackTrace();
}
System.out.println(” \tDo you want to continue (y/n):- “);
choice=in.readLine().charAt(0);
}while(choice!=’n’);
}
}
/*
Output:
H:\sem 4\Java\done>javac Directory.java
H:\sem 4\Java\done>java Directory
Select Operation
1. Add Contact
2. Search Contact
3. Delete Contact
4. Updtae Contact
Enter your choice:- 1
How many contact you want to add in database:4
Enter data the Name and Phone: santosh 8108241634
Record Inserted..
Enter data the Name and Phone: tejas 1234567890
Record Inserted..
Enter data the Name and Phone: nagesh 0987654321
Record Inserted..
Enter data the Name and Phone: prasad 4561237890
Record Inserted..
Do you want to continue (y/n):-y
Select Operation
1. Add Contact
2. Search Contact
3. Delete Contact
4. Updtae Contact
Enter your choice:- 2
Enter Name of student for contact Search: santosh
Contact no for santosh is 8108241634
Do you want to continue (y/n):-y
Select Operation
1. Add Contact
2. Search Contact
3. Delete Contact
4. Updtae Contact
Enter your choice:-3
Enter Name of student to delete from database : nagesh
Record deleted..
Do you want to continue (y/n):-y
Select Operation
1. Add Contact
2. Search Contact
3. Delete Contact
4. Updtae Contact
Enter your choice:-4
Enter data the Name and Phone for update: prasad 9876543210
Record Updated..
Select Operation
1. Add Contact
2. Search Contact
3. Delete Contact
4. Updtae Contact
Enter your choice:- 2
Enter Name of student for contact Search:prasad Contact no for prasad is 9876543210
Do you want to continue (y/n):-n
*/
Q)Write a servlet program for currency converter
Practical No.:
CODE:
//Index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<html> <body>
<form method=”post” action=”Currency”>
<br><br><br>
<center>
Convert this amount:<input type=”text” name=”currencyamount”>
of this type of currency
<select name=”currencyfrom”>
<option value=”” selected>Select a currency</option>
<option value=”1″>INDIA (IND)</option>
<option value=”66″>USA (USA)</option>
</select>
into this type of currency.
Date:
<select name=”currencyto”>
<option value=”” selected>All other currencies</option>
<option value=”1″>INDIA (IND)</option>
<option value=”66″>USA (USA)</option>
</select>
<input type=”submit” value=”Convert”>
</center>
</form>
</body></html>
//currency.java
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 Currency extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
float newamt;
float amt = Float.parseFloat(request.getParameter(“currencyamount”));
float currencyfrom = Float.parseFloat(request.getParameter(“currencyfrom”));
float currencyto = Float.parseFloat(request.getParameter(“currencyto”));
newamt = (amt / currencyto) * currencyfrom;
out.println(“<html><head>”);
out.println(“<title>Servlet Currency</title>”);
out.println(“</head><body><br><br><br><br>”);
out.println(“<h1 align=center>The Converted Currency is ” + newamt + “</h1>”);
out.println(“</body></html>”);
}
}
Output:
Q)Write a servlet program for Quiz Assignment
Practical No.:
CODE:
//index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<html>
<head>
Date:
<title>multiple-choice quiz form</title>
</head>
<body bgcolor=#ffffff>
<h3>Cryptography Quiz </h3>
<form method=”post” action=”Quiz”>
<BR>Enter your Name : <input type=”text” name=”name” value=””><BR>
<P>1. In cryptography, what is cipher?<BR>
<input type=”radio” name=”1″ value=”A”>
A. algorithm for performing encryption and decryption<BR>
<input type=”radio” name=”1″ value=”B”>B. encrypted message<BR>
<input type=”radio” name=”1″ value=”C”>C. both (a) and (b)<BR>
<input type=”radio” name=”1″ value=”D”>D. none of the mentioned<BR>
</p>
<P>2. The ________ is the message after transformation.<BR>
<input type=”radio” name=”2″ value=”A”>A. cipher text<BR>
<input type=”radio” name=”2″ value=”B”>B. plain text<BR>
<input type=”radio” name=”2″ value=”C”>C. secret text<BR>
<input type=”radio” name=”2″ value=”D”>D. none of the above<BR>
</p>
<P>3. A(n) ______ algorithm transforms cipher text to plaintext.<BR>
<input type=”radio” name=”3″ value=”A”>A. encryption<BR>
<input type=”radio” name=”3″ value=”B”>B. decryption<BR>
<input type=”radio” name=”3″ value=”C”>C. either (a) or (b)<BR>
<input type=”radio” name=”3″ value=”D”>D. neither (a) nor (b)<BR>
</p>
<P>4. The _______ is a number or a set of numbers on which the cipher operates.<BR>
<input type=”radio” name=”4″ value=”A”>A. cipher<BR>
<input type=”radio” name=”4″ value=”B”>B. secret<BR>
<input type=”radio” name=”4″ value=”C”>C. key<BR>
<input type=”radio” name=”4″ value=”D”>D. none of the above<BR>
</p>
<P>5. A combination of an encryption algorithm and a decryption algorithm is called a
________.<BR>
<input type=”radio” name=”5″ value=”A”>A. cipher<BR>
<input type=”radio” name=”5″ value=”B”>B. secret<BR>
<input type=”radio” name=”5″ value=”C”>C. key<BR>
<input type=”radio” name=”5″ value=”D”>D. none of the above<BR>
</p>
<br><br>
<input type=”submit” value=”Send Form”>
<input type=”reset” value=”Clear Form”>
</form>
</body>
</html>
// Quiz.java
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 NewServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name1 = request.getParameter(“name”);
String a1 = request.getParameter(“1″);
String a2 = request.getParameter(“2″);
String a3 = request.getParameter(“3″);
String a4 = request.getParameter(“4″);
String a5 = request.getParameter(“5″);
int cnt = 0;
if (a1.equals(“A”)) {
cnt++;
}
if (a2.equals(“A”)) {
cnt++;
}
if (a3.equals(“B”)) {
cnt++;
}
if (a4.equals(“C”)) {
cnt++;
}
if (a5.equals(“A”)) {
cnt++;
}
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<html><head>”);
out.println(“<title>Cryptography Quiz</title>”);
out.println(“</head><body><br><br><br><br>”);
out.println(“<Center><h1>Hi ” + name1 + “, you have got ” + cnt + “
score in Cryptography Quiz</h1><Center>”);
out.println(“</body></html>”);
out.close();
}}
//Output:
Q) Write a packages program for Animal-Animal interface, Mammal
Practical No.:
Date:
CODE:
// Mammal.java
package animals;
interface IAnimal
{
void Eat();
void Travel();
}
public class Mammal implements IAnimal
{
public void Eat()
{
System.out.println(“Eat of mammal “);
}
public void Travel()
{
System.out.println(“Travel of mammal “);
}
// Animals.java
import animals.*;
public class Animals
{
}
public static void main(String[] args)
{
Mammal m=new Mammal();
m.Eat();
m.Travel();
}
}
/*
Output:
G:\sem 4\Java\Om_java\done\Animal Interface\animals>javac Mammal.java
G:\sem 4\Java\Om_java\done\Animal Interface>java Animals
Eat of mammal
Travel of mammal
*/
Q) Write a program of Piped IO */
Practical No.:
CODE:
import java.util.*;
Date:
import java.io.*;
class Fibonacci extends Thread
{
private PipedWriter out = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t = Thread.currentThread();
t.setName(“Fibonacci”);
System.out.println(t.getName() + ” thread started”);
int fibo1=0,fibo2=1,fibo=0;
while(true)
{
try
{
fibo = fibo1 + fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(100);
}
catch(Exception e)
{
System.out.println(“Fibonacci:”+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName() + ” thread exiting”);
}
}
class Prime extends Thread
{
private PipedWriter out1 = new PipedWriter();
public PipedWriter getPipedWriter()
{
return out1;
}
public void run()
{
Thread t= Thread.currentThread();
t.setName(“Prime”);
System.out.println(t.getName() + ” thread Started…”);
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName() + ” thread exiting.”);
System.exit(0);
}
}
}
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
if(n==1 || n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
public class PipedIo
{
public static void main(String[] args) throws Exception
{
Thread t=Thread.currentThread();
t.setName(“Main”);
System.out.println(t.getName() + ” thread Started…”);
Fibonacci fibonacci = new Fibonacci();
Prime prime = new Prime();
PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
PipedReader ppr = new PipedReader(prime.getPipedWriter());
fibonacci.start();
prime.start();
int fib=fpr.read(), prm=ppr.read();
System.out.println(“The numbers common to PRIME and FIBONACCI:”);
while((fib!=-1) && (prm!=-1))
{
while(prm<=fib)
{
if(fib==prm)
System.out.println(prm);
prm=ppr.read();
}
fib=fpr.read();
}
System.out.println(t.getName() + ” thread exiting”);
}
}
/*
Output:
G:\sem 4\Java\Om_java>javac PipedIo.java
G:\sem 4\Java\Om_java>java PipedIo
Main thread Started…
Fibonacci thread started
Prime thread Started…
The numbers common to PRIME and FIBONACCI:
1
2
3
5
13
89
233
1597
Fibonacci thread exiting
28657
Main thread exiting
Prime thread exiting.
*/
Q) Write a program of Random IO
Practical No.:
CODE:
import java.io.*;
class RandomIO
{
public static void main(String args[])
RandomAccessFile file=null;
try
{
file=new RandomAccessFile(“rand.txt”,”rw”);
//writing to file
file.writeChar(‘X’);
file.writeInt(555);
file.writeDouble(3.1412);
file.seek(0); //go to the begining of file
//reading from file
System.out.println(“Record 0: ” +file.readChar());
System.out.println(“Record 1: ” + file.readInt());
Date:
System.out.println(“Record 2: ” + file.readDouble());
System.out.println();
file.seek(2); //go to the second item
System.out.println(“Record 1: “+file.readInt());
System.out.println();
file.seek(file.length());
file.writeBoolean(true); //write boolean value in the file
file.seek(4); //go to the third item
System.out.println(“Record 3: “+file.readBoolean());
file.close();
}
catch(IOException e)
{System.out.println(e);}
}
}
Output:
G:\sem 4\Java\Om_java>javac RandomIO.java
G:\sem 4\Java\Om_java>java RandomIO
Record 0: X
Record 1: 555
Record 2: 3.1412
Record 1: 555
Record 3: true
*/
Q) Write a servlet program to retrieve event based on date from database
Practical No.:
CODE:
//index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<html><body>
<form method=post action=schedule>
<br><br><br>
<center>
Enter Date: <input type=”text” name=”sdate” value=””>
<br><br>
<input type=”submit” value=”Submit”>
</center>
</form>
</body>
</html>
Date:
// schedule.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class schedule extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String sdate = request.getParameter(“sdate”);
String details = “”;
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:testx”, “”, “”);
java.sql.Statement smt = con.createStatement();
ResultSet res = smt.executeQuery(“Select Event from timetable where Tdate=’” + sdate +
“‘”);
if (res.next()) {
details = res.getString(1);
} else {
details = “Holiday”;
}
} catch (Exception e) {
}
out.println(“<html><head>”);
out.println(“<title>Time Table</title>”);
out.println(“</head><body><br><br><br><br>”);
out.println(“<Center><h1>On ” + sdate + “, There will be ” + details + “</h1><Center>”);
out.println(“</body></html>”);
out.close();
}}
Q)Write a servlet program to HttpSession (Web Page Counter)
Practical No.:
CODE:
import java.io.IOException;
Date:
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
int cnt = 1;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession hs = request.getSession(true);
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Date date = (Date) hs.getAttribute(“date”);
if (date != null) {
pw.print(“Last access: ” + date);
pw.print(“<br>Last Web page count: ” + cnt + “<br><br>”);
}
date = new Date();
hs.setAttribute(“date”, date);
cnt = cnt + 1;
pw.println(“Current date: ” + date);
pw.print(“<br>Current Web page count: ” + cnt + “<br>”);
}
}
//Output:
Q) Write a program demonstrate Division by zero Exception
Practical No.:
CODE:
class Division {
public static void main(String[] args) {
try {
int d = 24 / Integer.parseInt(args[0]);
System.out.println(“Division is:” + d);
} catch (ArithmeticException e1) {
System.out.println(“Division By Zero Exception”);
System.out.println(e1.getMessage());
}
}
}
Date:
/*
Output:
G:\sem 4\Java\Om_java\done>javac Division.java
G:\sem 4\Java\Om_java\done>java Division 0
Division By Zero Exception
/ by zero
*/
/*Write a program to demonstrate Negative Array Size Exception */
Practical No.:
public class exp
{
public static void main(String args[])
{
int a[]={-1,2,3,-4,5,6,-7};
for (int i = 0; i < 7; i++)
{
try
{
if(a[i]<0)
throw new NegativeArraySizeException(a[i] + ” is Negative number”);
else
Date:
System.out.println(a[i]);
}
catch(NegativeArraySizeException ex) { System.out.println(ex.getMessage()); }
}
}
}
/*
Output:
G:\sem 4\Java\done>javac exp.java
G:\sem 4\Java\done>java exp
-1 is Negative number
2
3
-4 is Negative number
5
6
-7 is Negative number
*/
/*Write a program to count the number of Vowel and Consonant in the given string. */
Practical No.:
public class VowelCounter {
public static void main(String args[]) {
Date:
String input = “bharati”;
char[] letters = input.toCharArray();
int cv = 0,cc = 0;
for (char c : letters) {
switch (c) {
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
cv++;
break;
default:
cc++;
}
}
System.out.println(“Number of vowels in String [" + input + "] is : ” + cv);
System.out.println(“Number of Consonant in String [" + input + "] is : ” + cc);
}
}
/*
Output:
H:\sem 4\Java\done>javac VowelCounter.java
H:\sem 4\Java\done>java VowelCounter
Number of vowels in String [bharati] is : 3
Number of Consonant in String [bharati] is : 4
*/
/* Write a program to demonstrate Negative Null Pointer Exception */
Practical No.:
class NullException
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}catch(NullPointerException e){
System.out.println(“Null Pointer Exception catch ..”);
System.out.println(e.getMessage());
}
}
}
/*
Output:
H:\sem 4\Java\done>javac NullException.java
H:\sem 4\Java\done>java NullException
Date:
Null Pointer Exception Catch…
null
*/
/* Write a program to demonstrate File Not Found Exception */
Practical No.:
import java.io.*;
public class FileException
{
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(“abc.txt”);
int k;
while((k = fis.read()) != -1)
{
System.out.print((char)k);
}
}
catch(FileNotFoundException e)
Date:
{
System.out.println(“The source file does not exist. “);
System.out.println(e.getMessage());
}
catch(Exception ex) {System.out.println(ex.getMessage());}
}
}
/*
Output:
H:\sem 4\Java\done>javac FileException.java
H:\sem 4\Java\done>java FileException
The source file does not exist.
abc.txt (The system cannot find the file specified)
*/
/* Write a program to demonstrate User Defined Exception */
Practical No.:
import java.lang.Exception;
import java.io.*;
class MyException extends Exception{
MyException(String Msg)
{
Date:
super(Msg);
}
}
class UserException{
public static void main(String[] args){
int a=0;
DataInputStream dis=new DataInputStream(System.in);
try
{
System.out.println(“Enter Age: “);
a=Integer.parseInt(dis.readLine());
if(a>15 && a<25)
System.out.println(“Your age is”+ a);
else
throw new MyException(“Given age value is invalid …”);
}
catch (MyException e){System.out.println(e.getMessage());}
catch (Exception e){System.out.println(e.getMessage());}
}
}
/*
Output:
H:\sem 4\Java\done>javac UserException.java
H:\sem 4\Java\done>java UserException
Enter Age: 10
Given age value is invalid …
*/
/* Write a program to draw scientific calculator */
Practical No.:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
/*<applet code=”Cal” width=300 height=300></applet>*/
public class Cal extends Applet implements ActionListener
{
String msg=” “;
int n1,n2;
double result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,res,sin,cos,tan,sqrt,pow;
char OP;
public void init()
{
Date:
t1=new TextField(10);
setLayout(new GridLayout(6,4));
for(int i=0;i<10;i++)
b[i]=new Button(“”+i);
add=new Button(“+”);
sub=new Button(“-”);
mul=new Button(“*”);
div=new Button(“/”);
mod=new Button(“%”);
sin=new Button(“Sin”);
cos=new Button(“Cos”);
tan=new Button(“Tan”);
sqrt=new Button(“SQRT”);
pow=new Button(“x^n”);
clear=new Button(“Clear”);
res=new Button(“Result”);
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
add(b[i]);
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(pow);
add(sqrt);
add(tan);
add(cos);
add(sin);
add(clear);
add(res);
for(int i=0;i<10;i++)
b[i].addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
pow.addActionListener(this);
sin.addActionListener(this);
cos.addActionListener(this);
tan.addActionListener(this);
sqrt.addActionListener(this);
clear.addActionListener(this);
res.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else if(str.equals(“+”))
{
n1=Integer.parseInt(t1.getText());
OP=’+’;
t1.setText(“”);
}
else if(str.equals(“-”))
{
n1=Integer.parseInt(t1.getText());
OP=’-’;
t1.setText(“”);
}
else if(str.equals(“*”))
{
n1=Integer.parseInt(t1.getText());
OP=’*’;
t1.setText(“”);
}
else if(str.equals(“/”))
{
n1=Integer.parseInt(t1.getText());
OP=’/’;
t1.setText(“”);
}
else if(str.equals(“%”))
{
n1=Integer.parseInt(t1.getText());
OP=’%’;
t1.setText(“”);
}
else if(str.equals(“Sin”))
{
n1=Integer.parseInt(t1.getText());
OP=’s’;
t1.setText(“”);
}
else if(str.equals(“Cos”))
{
n1=Integer.parseInt(t1.getText());
OP=’c’;
t1.setText(“”);
}
else if(str.equals(“Tan”))
{
n1=Integer.parseInt(t1.getText());
OP=’t’;
t1.setText(“”);
}
else if(str.equals(“SQRT”))
{
n1=Integer.parseInt(t1.getText());
OP=’(‘;
t1.setText(“”);
}
else if(str.equals(“x^n”))
{
n1=Integer.parseInt(t1.getText());
OP=’^’;
t1.setText(“”);
}
if(str.equals(“Sin”))
{
result=Math.sin(n1);
t1.setText(String.valueOf(result));
}
if(str.equals(“Cos”))
{
result=Math.cos(n1);
t1.setText(String.valueOf(result));
}
if(str.equals(“Tan”))
{
result=Math.tan(n1);
t1.setText(String.valueOf(result));
}
if(str.equals(“SQRT”))
{
result=Math.sqrt(n1);
t1.setText(String.valueOf(result));
}
if(str.equals(“Result”))
{
n2=Integer.parseInt(t1.getText());
if(OP==’+’)
result=n1+n2;
else if(OP==’-’)
result=n1-n2;
else if(OP==’*’)
result=n1*n2;
else if (OP==’^’)
{
if (n2==0)
result=1;
else
{
for (int i=1;i<n2;i++)
n1*=n1;
result=n1;
}
}
else if(OP==’/’)
{
if(n2!=0)
result=n1/n2;
else
t1.setText(“Invalid Values”);
}
else if(OP==’%’)
{
if(n2!=0)
result=n1%n2;
else
t1.setText(“Invalid Values”);
}
t1.setText(“”+result);
}
if(str.equals(“Clear”))
t1.setText(“”);
}
}
/*
Output:
H:\sem 4\Java\done>javac Cal.java
H:\sem 4\Java\done>appletviewer Cal.java
*/
/*Write a jsp program for Grade Calculator */
Practical No.:
Date:
//Index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<form action=”calculate.jsp” method=”post”>
<h1 align =”center”> Grade Calculator </h1>
<p>Student Name: <input type=”text” name=”name”><br>
<p>Lab Attended <input type=”text” name=”txt1″>
Total Lab <input type=”text” name=”txt2″><br>
<p>Attendance <input type=”text” name=”txt3″>
Total Attendance <input type=”text” name=”txt4″><br>
<p>Mid Term Marks<input type=”text” name=”txt5″>
Total Marks<input type=”text” name=”txt6″><br>
<p>Final Marks<input type=”text” name=”txt7″>
Total Marks<input type=”text” name=”txt8″><br>
<p align=”center”><input type=”submit” value=”Submit”>
</form>
</body>
</html>
// calculate.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<body><h2>
<%
String name1 = request.getParameter(“name”);
int s1 = Integer.parseInt(request.getParameter(“txt1″));
int s2 = Integer.parseInt(request.getParameter(“txt2″));
int s3 = Integer.parseInt(request.getParameter(“txt3″));
int s4 = Integer.parseInt(request.getParameter(“txt4″));
int s5 = Integer.parseInt(request.getParameter(“txt5″));
int s6 = Integer.parseInt(request.getParameter(“txt6″));
int s7 = Integer.parseInt(request.getParameter(“txt7″));
int s8 = Integer.parseInt(request.getParameter(“txt8″));
int tot = s5 + s7;
int sum = s6 + s8;
int per = tot * 100 / sum;
out.println(“<br> Student Name: ” + name1);
out.println(“<br> Lab Attended Percentage: ” + s1 * 100 / s2);
out.println(“<br> Lec. Attended Percentage: ” + s3 * 100 / s4);
out.println(“<br> Mid Term Marks Percentage: ” + s5 * 100 / s6);
out.println(“<br> Final Marks Percentage: ” + s7 * 100 / s8);
out.println(“<br> Total Marks Percentage: ” + per);
String ch = “fail”;
if (per > 80) {
ch = “Outstanding”;
} else if (per > 60) {
ch = “A”;
} else if (per < 60 && per >= 50) {
ch = “B”;
} else if (per < 50 && per >= 45) {
ch = “C”;
}
if (per < 45) {
ch = “Fail”;
}
out.println(“<br> Your grade Is: ” + ch);
%></h2>
</body>
</html>
//Output:
/*Write a program on session bean stateless and statefull*/
Practical No.:
//calculatorBeanLocal.java
package sample.ejb;
import javax.ejb.Local;
@Local
Date:
public interface calculatorBeanLocal {
Integer beanAdd(int a, int b);
Integer beansub(int a, int b);
}
//calculatorBeanLocal.java
package sample.ejb;
import javax.ejb.Stateless;
@Stateless
public class calculatorBean implements calculatorBeanLocal {
@Override
public Integer beanAdd(int a, int b) {
return (a + b);
}
public Integer beansub(int a, int b) {
return (a – b);
}
}
//Index.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form action=SessionBeanServlet>
<input type=”submit”>
</form>
</body>
</html>
//SessionBeanServlet.java
package sample.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sample.ejb.calculatorBeanLocal;
@WebServlet(name = “SessionBeanServlet”, urlPatterns = {“/SessionBeanServlet”})
public class SessionBeanServlet extends HttpServlet {
@EJB
private calculatorBeanLocal calculatorBean;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
try {
int a = 9;
int b = 3;
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet SessionBeanServlet</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<br>Addition of two number is ” + calculatorBean.beanAdd(a, b));
out.println(“<br>Subtraction of two number is ” + calculatorBean.beansub(a, b));
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
}
Output:
/*Write a program on Message Driven Bean*/
Practical No.:
//NewServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.*;
Date:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = “NewServlet”, urlPatterns = {“/NewServlet”})
public class NewServlet extends HttpServlet {
@Resource(mappedName = “jms/dest”)
private Queue dest;
@Resource(mappedName = “jms/queue”)
private ConnectionFactory queue;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
String str = request.getParameter(“msg”);
try {
out.println(“<html>”);
out.println(“<head>”);
out.println(“</head>”);
out.println(“<body>”);
try {
sendJMSMessageToDest(str);
} catch (JMSException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
out.println(“<h1> Your Message ” + str + ” has been send to server </h1>”);
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
private Message createJMSMessageForjmsDest(Session session, Object messageData)
throws JMSException {
// TODO create and populate message to send
TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
}
private void sendJMSMessageToDest(Object messageData) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = queue.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(dest);
messageProducer.send(createJMSMessageForjmsDest(session, messageData));
} finally {
if (session != null) {
try {
session.close();
} catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, “Cannot close session”,
e);
}
}
if (connection != null) {
connection.close();
}
}
}
}
//Enterprise Beans MBean
package com.message;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(mappedName = “jms/dest”, activationConfig = {
@ActivationConfigProperty(propertyName = “acknowledgeMode”, propertyValue = “Autoacknowledge”),
@ActivationConfigProperty(propertyName = “destinationType”, propertyValue =
“javax.jms.Queue”)
})
public class MBean implements MessageListener {
public MBean() {
}
@Override
public void onMessage(Message message) {
try {
TextMessage tmsg=null;
tmsg=(TextMessage)message;
System.out.println(tmsg.getText());
} catch (JMSException ex) {
Logger.getLogger(MBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//Index.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<form action=’NewServlet’>
<h1> Enter Your Message <input type=”text” name=”msg”>
<input type=”submit”>
</h1> </form>
</body>
</html>
//Output:
/*Write a program on Entity Bean*/
Practical No.:
//AbstractFacade.java
package mypack;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
Date:
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] – range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}}
//Emp.java
package mypack;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = “EMP”)
@XmlRootElement
@NamedQueries({
@NamedQuery(name = “Emp.findAll”, query = “SELECT e FROM Emp e”),
@NamedQuery(name = “Emp.findByEmpno”, query = “SELECT e FROM Emp e WHERE
e.empno = :empno”),
@NamedQuery(name = “Emp.findByEname”, query = “SELECT e FROM Emp e WHERE
e.ename = :ename”)})
public class Emp implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = “EMPNO”)
private Integer empno;
@Size(max = 20)
@Column(name = “ENAME”)
private String ename;
public Emp() {
}
public Emp(Integer empno) {
this.empno = empno;
}
public Integer getEmpno() {
return empno;
}
public void setEmpno(Integer empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
@Override
public int hashCode() {
int hash = 0;
hash += (empno != null ? empno.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Emp)) {
return false;
}
Emp other = (Emp) object;
if ((this.empno == null && other.empno != null) || (this.empno != null &&
!this.empno.equals(other.empno))) {
return false;
}
return true;
}
@Override
public String toString() {
return “mypack.Emp[ empno=" + empno + " ]“;
}
}
// EmpFacade.java
package mypack;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class EmpFacade extends AbstractFacade<Emp> implements EmpFacadeLocal {
@PersistenceContext(unitName = “EBean-ejbPU”)
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public EmpFacade() {
super(Emp.class);
}
@Override
public void persist(Object obj) {
em.persist(obj);
}
@Override
public void addsEmp(int eid, String ename) {
Emp obj = new Emp();
obj.setEmpno(eid);
obj.setEname(ename);
persist(obj);
}}
// EmpFacadeLocal.java
package mypack;
import java.util.List;
import javax.ejb.Local;
@Local
public interface EmpFacadeLocal {
void create(Emp emp);
void edit(Emp emp);
void remove(Emp emp);
Emp find(Object id);
List<Emp> findAll();
List<Emp> findRange(int[] range);
int count();
public void persist(java.lang.Object obj);
public void addsEmp(int eid, String ename);
}
// empEntity.java
package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class empEntity extends HttpServlet {
@EJB
private EmpFacadeLocal empFacade;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();
try {
empFacade.addsEmp(11, “Santosh”);
empFacade.addsEmp(12, “Tejas”);
empFacade.addsEmp(13, “Prasad”);
empFacade.addsEmp(14, “Nagesh”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet NewServlet</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“<h1>Record inserted successfully” + “</h1>”);
out.println(“</body>”);
out.println(“</html>”);
} finally {
out.close();
}
}
@Override
public String getServletInfo() {
return “Short description”;
}}
//Output:
/*Write a program on struts */
Practical No.:
//register.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”s” uri=”/struts-tags” %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
Date:
<body>
<h1>Registration Form</h1>
<s:form action=”registerAction”>
<s:textfield name=”id” label=”Enter id :”>
</s:textfield>
<s:textfield name=”uname” label=”Enter Username :”>
</s:textfield>
<s:password name=”upass” label=”Enter Password :”>
</s:password>
<s:textfield name=”email” label=”Enter Email-id :”>
</s:textfield>
<s:textfield name=”age” label=”Enter Age:”>
</s:textfield>
<s:submit value=”Submit”>
</s:submit>
</s:form>
</body>
</html>
//login.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Well come <%=request.getParameter(“uname”)%> ,</h1>
</body>
</html>
//error.jsp
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Error Catch.</h1>
</body>
</html>
//struts.xml
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>
<struts>
<!– Configuration for the default package. –>
<package name=”default” extends=”struts-default” namespace=”/”>
<action name=”registerAction” class=”com.myapp.mode.Action.RegisterActionSupport”>
<result name=”input”>/register.jsp </result>
<result name=”success”>/login.jsp </result>
<result name=”error”>/error.jsp </result>
</action>
</package>
</struts>
//RegisterActionSupport-validation.xml
<!DOCTYPE validators PUBLIC
“-//Apache Struts//XWork Validator 1.0.2//EN”
“http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd”>
<validators>
<field name=”id”>
<field-validator type=”requiredstring”>
<message>
The id is required.
</message>
</field-validator>
</field>
<field name=”uname”>
<field-validator type=”requiredstring”>
<message>
The name is required.
</message>
</field-validator>
</field>
<field name=”upass”>
<field-validator type=”requiredstring”>
<message>
The pass is required.
</message>
</field-validator>
</field>
<field nme=”email”>
<field-validator type=”requiredstring”>
<message>
email is required.
</message>
</field-validator>
<field-validator type=”email”>
<message>
email is invalid.
</message>
</field-validator>
</field>
<field name=”age”>
<field-validator type=”required”>
<message>You must enter a value for age.</message>
</field-validator>
<field-validator type=”int”>
<param name=”min”>6</param>
<param name=”max”>20</param>
<message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
</field-validator>
</field>
</validators>
//RegisterActionSupport.java
package com.myapp.mode.Action;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterActionSupport extends ActionSupport {
private String id, uname;
public int getAge() {
return age;
public void setAge(int age) {
public String getEmail() {
}
this.age = age;
return email;
public void setEmail(String email) {
public String getId() {
return id;
public void setId(String id) {
public String getUname() {
this.email = email;
}
}
}
return uname; }
this.uname = uname;
return upass;
public void setUpass(String upass) {
private String upass;
}
this.id = id;
public void setUname(String uname) {
public String getUpass() {
}
}
this.upass = upass;
}
}
private String email;
private int age;
public RegisterActionSupport() {
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
//Output:
/*Write a program on struts 2 */
Practical No.:
//Index.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
Date:
<form action=”greet”>
Enter Name: <input type=”text” name=”uname”>
<input type=”submit” value=”Greet All”>
</form>
</body>
</html>
//success.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1><%=request.getParameter(“uname”)%> Sucessfully Greeted to All</h1>
</body>
</html>
//struts.xml
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>
<struts>
<!– Configuration for the default package. –>
<package name=”default” extends=”struts-default” namespace=”/”>
<action name=”greet” class=”GreetFromStruts.GreetAll” method=”execute”>
<result name=”SUCCESS”>/success.jsp</result>
</action>
</package>
</struts>
//GreetAll.java
package GreetFromStruts;
import com.opensymphony.xwork2.ActionSupport;
public class GreetAll extends ActionSupport {
public GreetAll() {
}
@Override
public String execute() throws Exception {
return “SUCCESS”;
}
}
//Output:
/*Write a program to create multiple thread and implements thread methods */
Practical No.:
Date:
class NewThread implements Runnable {
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println(“New thread: ” + t);
t.start();
}
public void run()
try
{
{
for(int i = 15; i > 0; i–)
{
System.out.println(name + “: ” + i);
Thread.sleep(200);
}
} catch (InterruptedException e) {System.out.println(name + ” interrupted.”);}
System.out.println(name + ” exiting.”);
}}
class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread(“One”);
NewThread ob2 = new NewThread(“Two”);
try {
Thread.sleep(1000);
ob1.t.suspend();
System.out.println(“Suspending thread One”);
Thread.sleep(500);
ob1.t.resume();
System.out.println(“Resuming thread One”);
ob2.t.suspend();
System.out.println(“Suspending thread Two”);
Thread.sleep(1000);
ob2.t.resume();
System.out.println(“Resuming thread Two”);
} catch (InterruptedException e) {System.out.println(“Main thread Interrupted”);}
try {
System.out.println(“Waiting for threads to finish.”);
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {System.out.println(“Main thread Interrupted”); }
System.out.println(“Main thread exiting.”); }}
/*
Output:
G:\sem 4\Java\done>javac SuspendResume.java
G:\sem 4\Java\done>java SuspendResume
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
One: 15
Two: 15
One: 14
Two: 14
One: 13
Two: 13
Two: 12
One: 12
One: 11
Two: 11
Two: 10
Suspending thread One
Two: 9
Two: 8
One: 10
Resuming thread One
Suspending thread Two
One: 9
One: 8
One: 7
One: 6
Two: 7
Resuming thread Two
Waiting for threads to finish.
One: 5
Two: 6
One: 4
One: 3
Two: 5
Two: 4
One: 2
Two: 3
One: 1
One exiting.
Two: 2
Two: 1
Two exiting.
Main thread exiting.
*/
/*Write a program to create multiple thread and implements thread methods */
Practical No.:
Date:
import java.io.*;
class NewThreadAlive implements Runnable{
String name;
Thread t;
NewThreadAlive(String msg) {
name=msg;
t=new Thread(this,”name”);
System.out.println(“current thread “+name);
t.start();
}
public void run(){
try{
for(int i=5;i>=1;i–)
{
System.out.println(name+” “+i);
Thread.sleep(1000);
}
}catch(Exception e){System.out.println(e);}
System.out.println(name+” exiting”);
}
public static void main(String args[]) {
NewThreadAlive obj1=new NewThreadAlive(“one”);
NewThreadAlive obj2=new NewThreadAlive(“two”);
NewThreadAlive obj3=new NewThreadAlive(“three”);
System.out.println(“Thread one is alive “+obj1.t.isAlive());
System.out.println(“Thread two is alive “+obj2.t.isAlive());
System.out.println(“Thread three is alive “+obj3.t.isAlive());
try{
System.out.println(“waiting for thread to finish”);
obj1.t.join();
obj2.t.join();
obj3.t.join();
}catch(Exception e){ System.out.println(e);}
System.out.println(“Thread one is alive “+obj1.t.isAlive());
System.out.println(“Thread two is alive “+obj2.t.isAlive());
System.out.println(“Thread three is alive “+obj3.t.isAlive());
}
}
/*
Output:
G:\sem 4\Java\done>javac NewThreadAlive.java
G:\sem 4\Java\done>java NewThreadAlive
current thread one
current thread two
one 5
current thread three
two 5
Thread one is alive true
three 5
Thread two is alive true
Thread three is alive true
waiting for thread to finish
three 4
one 4
two 4
two 3
three 3
one 3
two 2
three 2
one 2
two 1
one 1
three 1
two exiting
three exiting
one exiting
Thread one is alive false
Thread two is alive false
Thread three is alive false
*/
/*Write a jsp program for Login Authentication using JDBC */
Practical No.:
//index.html
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<h1>Login Form</h1>
<form action=”login.jsp” method=”post” >
<br>User Name :<input type=”text” name=”uname”>
<br>Password :<input type=”password” name=”pass”>
<br><input type=”submit” value=”Login”>\
</form></body>
</html>
//login.jsp
<%@page import=”java.sql.DriverManager”%>
<%@page import=”java.sql.ResultSet”%>
<%@page import=”java.sql.Statement”%>
<%@page import=”java.sql.Connection”%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
Date:
<html> <head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body> <h2>
<%
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con = DriverManager.getConnection(“jdbc:odbc:testx”, “”, “”);
Statement smt = con.createStatement();
String uname = request.getParameter(“uname”);
String pass = request.getParameter(“pass”);
ResultSet res = smt.executeQuery(“Select * from login where uname=’” + uname + “‘ and
pass=’” + pass + “‘ “);
if (res.next()) {
out.println(“User ” + uname + ” Successfully logged in… “);
} else {
out.println(“Enter proper login detail..”);
}
} catch (java.lang.Exception ex) { out.println(“Error in connection”);
%>
</h2>
</body> </html>
//Output:
}
/*Write a jsp program for using Cookies */
Practical No.:
Date:
//index.jsp
<html>
<body>
<form method=post action=addcookie.jsp>
<br> <center>
Enter Information for Cookies: <input type=”text” name=”data” value=””>
<br> <input type=”submit” value=”Submit”>
</center> </form>
</body>
</html>
//addcookies.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<%
String data = request.getParameter(“data”);
Cookie cookie = new Cookie(“My_Cookie”, data);
response.addCookie(cookie);
out.println(“<Center><h1>My Cookies Details are ” + data + “<Center>”);
%>
</body>
</html>
//getcookies.jsp
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
</head>
<body>
<%
String data, values;
Cookie[] cookie = request.getCookies();
for (int i = 0; i < cookie.length; i++) {
data = cookie[i].getName();
values = cookie[i].getValue();
out.println(“<h2>My Cookies Name = ” + data + ” and My Cookies value = ” + values +
“</h2>”);
}
%>
//Output:
</body> </html>
/*Write a jsp program for Error Handling */
Practical No.:
//index.jsp
<%@ page errorPage=”ShowError.jsp” %>
<html>
<head>
Date:
/head>
<body>
<%
int x = 1;
if (x == 1)
{ throw new RuntimeException(“Error condition!!!”); }
%>
</body>
</html>
// ShowError.jsp
<%@ page isErrorPage=”true” %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps…</h1> <p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre> <% out.println(exception);%> </pre>
</body>
</html>
//Output:
/*Write a jsp program for Session management */
Practical No.:
//index.jsp
<%@ page import=”java.io.*,java.util.*” %>
<%
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = “Welcome Back to my website”;
Integer visitCount = new Integer(0);
String visitCountKey = new String(“visitCount”);
String userIDKey = new String(“userID”);
String userID = new String(“BVIMIT”);
if (session.isNew()) {
title = “Welcome to my website”;
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer) session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String) session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount) ; %>
<html>
<body>
<center> <h1>Session Tracking</h1> </center>
<table border=”1″ align=”center”>
<tr bgcolor=”#949494″>
Date:
<th>Session info</th>
<th>Value</th>
</tr>
<tr> <td>id</td>
<td><% out.print(session.getId());%></td>
</tr>
<tr> <td>Creation Time</td>
<td><% out.print(createTime);%></td>
</tr>
<tr> <td>Time of Last Access</td>
<td><% out.print(lastAccessTime);%></td>
</tr>
<tr> <td>User ID</td>
<td><% out.print(userID);%></td>
</tr>
<tr> <td>Number of visits</td>
<td><% out.print(visitCount);%></td>
</tr>
</table>
</body></html>
//Output:
/*Write a jsp program for Session management */
Practical No.:
Date:
//index.jsp
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id=”test” class=”action.TestBean” />
<jsp:setProperty name=”test” property=”message” value=”Hello JSP…” />
<p>Got message….</p>
<jsp:getProperty name=”test” property=”message” />
</center>
</body>
</html>
// TestBean.java
package action;
public class TestBean {
private String message = “No message specified”;
public String getMessage() {
return (message);
}
public void setMessage(String message) {
this.message = message;
}
}
//Output:
/*WAP for super shop which will select the item from database& display a bill*/
Practical No.:
import java.io.DataInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
class Shopping {
Connection con;
Statement st;
ResultSet rs;
boolean ch = true;
String itemName, str;
int choice, price;
DataInputStream dis;
public Shopping() {
Date:
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con = DriverManager.getConnection(“jdbc:odbc:testx”);
st = con.createStatement();
} catch (Exception ex) {
System.out.println(ex);
}
try {
dis = new DataInputStream(System.in);
} catch (Exception ed) {
System.out.println(ed);
}
while (ch) {
try {
System.out.println(“\t Shopping System “);
System.out.println(“———————————–”);
System.out.println(“Select your Choice “);
System.out.println(“1 : Insert “);
System.out.println(“2 : Delete “);
System.out.println(“3 : Update “);
System.out.println(“4 : Display”);
System.out.println(“5 : Display all”);
System.out.println(“6 : Bill”);
System.out.println(“7 : Exit”);
choice = Integer.parseInt(dis.readLine());
if (choice == 1) {
Insert();
} else if (choice == 2) {
Delete();
} else if (choice == 3) {
Update();
} else if (choice == 4) {
Display(4);
} else if (choice == 5) {
Display(5);
} else if (choice == 6) {
Bill();
} else if (choice == 7) {
System.out.println(“Shopping System Closing……..”);
Thread.sleep(5000);
ch = false;
} else {
System.out.println(“Please Select Proper choice….”);
Thread.sleep(5000);
System.exit(0);
}
} catch (Exception exx) {
System.out.println(exx);
}
} }
private void Insert() {
try {
System.out.println(“Enter data for inserting new items”);
System.out.print(“Item Name”);
itemName = dis.readLine();
System.out.print(“\nItem Price”);
price = Integer.parseInt(dis.readLine());
str = “insert into tblItem(Name,price) values(‘” + itemName + “‘,’” + price + “‘)”;
st.executeUpdate(str);
System.out.println(“Data Inserted…..”);
Thread.sleep(5000);
st.clearBatch();
} catch (Exception ex) {
System.out.println(ex);
}
}
private void Delete() {
try {
System.out.println(“Enter Item name which you wants to delete.”);
itemName = dis.readLine();
str = “delete from tblItem where Name=’” + itemName + “‘”;
st.executeUpdate(str);
System.out.println(“Data Deleted…..”);
Thread.sleep(5000);
st.clearBatch();
} catch (Exception ex) {
System.out.println(ex);
}
}
private void Update() {
try {
System.out.println(“Enter Item name which you wants to Update.”);
itemName = dis.readLine();
str = “update tblItem set price=” + price + ” where Name=’” + itemName + “‘”;
st.executeUpdate(str);
System.out.println(“Data updated…..”);
Thread.sleep(5000);
st.clearBatch();
} catch (Exception ex) {
System.out.println(ex);
} }
private void Display(int i) {
try {
if (i == 4) {
try {
str = “select * from tblItem”;
rs = st.executeQuery(str);
System.out.println(“Item Name\t Price”);
while (rs.next()) {
System.out.println(rs.getString(“Name”) + “\t” + rs.getInt(“Price”));
Thread.sleep(500);
}
rs.close();
st.clearBatch();
} catch (Exception ex) {
System.out.println(ex);
}
} else if (i == 5) {
try {
str = “select * from tblItem”;
rs = st.executeQuery(str);
System.out.println(“Item Name\t Price”);
System.out.println(“————————-”);
while (rs.next()) {
System.out.println(rs.getString(“Name”) + “\t\t ” + rs.getInt(“Price”));
Thread.sleep(500);
}
rs.close();
st.clearBatch();
} catch (Exception ex) { System.out.println(ex); } }
} catch (Exception ex) { System.out.println(ex); }
}
private void Bill() {
try {
try {
str = “select * from tblItem”;
rs = st.executeQuery(str);
System.out.println(“Item Name”);
System.out.println(“—————”);
while (rs.next()) {
System.out.println(rs.getString(“Name”) + “\t”);
Thread.sleep(500);
}
rs.close();
st.clearBatch();
} catch (Exception ex) { System.out.println(ex); }
int co, sum = 0;
System.out.println(“Enter total count of item which you wants to buy….”);
co = Integer.parseInt(dis.readLine());
String item[] = new String[co + 1];
for (int i = 0; i < co; i++) {
System.out.print(“Item Name : “);
item[i] = dis.readLine();
System.out.println(“”);
}
for (int i = 0; i < item.length; i++) {
str = “select * from tblItem where Name=’” + item[i] + “‘”;
rs = st.executeQuery(str);
while (rs.next()) {
sum = sum + rs.getInt(“Price”);
Thread.sleep(500);
}
st.clearBatch();
rs.close();
}
System.out.println(“Total Bill : ” + sum);
} catch (Exception ex) {
System.out.println(ex);
}
}}
class Shop {
public static void main(String srg[]) {
Shopping s = new Shopping();
}
}
/*
Output:
G:\sem 4\Java\done>javac Shop.java
G:\sem 4\Java\done>java Shop
Shopping System
———————————–
1 : Insert
2 : Delete
3 : Update
4 : Display
5 : Display all
6 : Bill
7 : Exit
Select your Choice : 6
Item Name
—————
Keyboard
Mouse
Hard Disk
Ram
Rom
Enter total count of item which you wants to buy..: 3
Item Name : Ram
Item Name : Rom
Item Name : Mouse
Total Bill : 1450
Shopping System
———————————–
1 : Insert
2 : Delete
3 : Update
4 : Display
5 : Display all
6 : Bill
7 : Exit
Select your Choice :7
Shopping System Closing……..
*/
Practical No:
Q) Write a program for Suspending and resuming a thread for Java 2.
CODE:
class NewThread implements Runnable
{
String name;
Thread t;
boolean suspendFlag;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println(“New thread: ” + t);
suspendFlag = false;
t.start();
}
public void run()
{
try
{
for(int i = 15; i > 0; i–)
{
System.out.println(name + “: ” + i);
Thread.sleep(200);
synchronized(this)
{
while(suspendFlag)
{
wait();
}
}
}
}
catch (InterruptedException e)
{
System.out.println(name + ” interrupted.”);
}
System.out.println(name + ” exiting.”);
}
void mysuspend()
{
suspendFlag = true;
}
synchronized void myresume()
{
suspendFlag = false;
notify();
}
}
public class SuspendResume
{
public static void main(String args[])
{
NewThread ob1 = new NewThread(“One”);
NewThread ob2 = new NewThread(“Two”);
try
{
Thread.sleep(1000);
ob1.mysuspend();
System.out.println(“Suspending thread One”);
Thread.sleep(1000);
ob1.myresume();
System.out.println(“Resuming thread One”);
ob2.mysuspend();
System.out.println(“Suspending thread Two”);
Thread.sleep(1000);
ob2.myresume();
System.out.println(“Resuming thread Two”);
}
catch (InterruptedException e)
{
System.out.println(“Main thread Interrupted”);
}
try
{
System.out.println(“Waiting for threads to finish.”);
ob1.t.join();
ob2.t.join();
}
catch (InterruptedException e)
{
System.out.println(“Main thread Interrupted”);
}
System.out.println(“Main thread exiting.”);
}
}
Output:
Practical No:
Q) WAP which create threads with different priority
a)
Simple Priority
CODE:
class thrun implements Runnable
{
Thread t;
boolean runn = true;
thrun(String st,int p)
{
t = new Thread(this,st);
t.setPriority(p);
t.start();
}
public void run()
{
System.out.println(“Thread name : ” + t.getName());
System.out.println(“Thread Priority : ” + t.getPriority());
}
}
class priority{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
thrun t1 = new thrun(“Thread1″,Thread.NORM_PRIORITY + 2);
thrun t2 = new thrun(“Thread2″,Thread.NORM_PRIORITY – 2);
System.out.println(“Main Thread : ” + Thread.currentThread());
System.out.println(“Main Thread Priority : ” + Thread.currentThread().getPriority());
}
}
Output:
b)Is Alive
import java.io.*;
class NewThreadAlive implements Runnable
{
String name;
Thread t;
NewThreadAlive(String msg)
{
name=msg;
t=new Thread(this,”name”);
System.out.println(“current thread “+name);
t.start();
}
public void run()
{
try
{
for(int i=5;i>=1;i–)
{
System.out.println(name+” “+i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(name+” exiting”);
}
public static void main(String args[])
{
NewThreadAlive obj1=new NewThreadAlive(“one”);
NewThreadAlive obj2=new NewThreadAlive(“two”);
NewThreadAlive obj3=new NewThreadAlive(“three”);
System.out.println(“Thread one is alive “+obj1.t.isAlive());
System.out.println(“Thread two is alive “+obj2.t.isAlive());
System.out.println(“Thread three is alive “+obj3.t.isAlive());
try
{
System.out.println(“waiting for thread to finish”);
obj1.t.join();
obj2.t.join();
obj3.t.join();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(“Thread one is alive “+obj1.t.isAlive());
System.out.println(“Thread two is alive “+obj2.t.isAlive());
System.out.println(“Thread three is alive “+obj3.t.isAlive());
}
}
Output:
b)
Join
CODE:
class NewThread implements Runnable
{
String name;
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println(“New thread: ” + t);
t.start();
}
public void run()
{
try
{
for(int i = 5; i > 0; i–)
{
System.out.println(name + “: ” + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + ” interrupted.”);
}
System.out.println(name + ” exiting.”);
}
}
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread(“One”);
NewThread ob2 = new NewThread(“Two”);
NewThread ob3 = new NewThread(“Three”);
System.out.println(“Thread One is alive: “+ ob1.t.isAlive());
System.out.println(“Thread Two is alive: “+ ob2.t.isAlive());
System.out.println(“Thread Three is alive: “+ ob3.t.isAlive());
try
{
System.out.println(“Waiting for threads to finish.”);
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println(“Main thread Interrupted”);
}
System.out.println(“Thread One is alive: “+ ob1.t.isAlive());
System.out.println(“Thread Two is alive: “+ ob2.t.isAlive());
System.out.println(“Thread Three is alive: “+ ob3.t.isAlive());
System.out.println(“Main thread exiting.”);
}
}
Output:
c)
Set Priority
CODE:
import java.io.*;
class clicker implements Runnable
{
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p)
{
t = new Thread(this);
t.setPriority(p);
}
public void run()
{
while (running)
{
click++;
}
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
class HiLoPri
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY – 2);
lo.start();
hi.start();
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println(“Main thread interrupted.”);
}
lo.stop();
hi.stop();
try
{
hi.t.join();
lo.t.join();
}
catch (InterruptedException e)
{
System.out.println(“InterruptedException caught”);
}
System.out.println(“Low-priority thread: ” + lo.click);
System.out.println(“High-priority thread: ” + hi.click);
}
}
Output:
Practical No:
Q) Write a Program to concatinate 2 files using BufferedInputStream and
BufferedOutputStream Classes.
CODE:
import java.io.*;
class ConcatFile
{
public static void main(String args[])
{
try{
FileInputStream file1=null;
FileInputStream file2=null;
SequenceInputStream file3=null;
file1=new FileInputStream(“file1.dat”);
file2=new FileInputStream(“file2.dat”);
file3=new SequenceInputStream(file1,file2);
BufferedInputStream inbuffer=new BufferedInputStream(file3);
BufferedOutputStream outbuffer=new BufferedOutputStream(System.out);
int ch;
while((ch=inbuffer.read())!=-1)
{
outbuffer.write((char)ch);
}
inbuffer.close();
outbuffer.close();
file1.close();
file2.close();
}
catch(IOException ioe){
System.out.println(ioe);}
}
}
Output:
===========================================
System.out.println(“”);
}
for (int i = 0; i < item.length; i++) {
str=”select * from tblItem where Name=’”+item[i]+”‘”;
rs= st.executeQuery(str);
while(rs.next()){
sum=sum+rs.getInt(“Price”);
Thread.sleep(500);
}
st.clearBatch();
rs.close();
}
System.out.println(“Total Bill : “+sum);
}
catch(Exception ex){
System.out.println(ex);
}
}
}======================
) Write a Program on jdbc to store telephone directory implement all operation
PROGRAM:
package phonedirectory;
import java.awt.Choice;
import java.io.DataInputStream;
public class PhoneDirectory
{
public static void main(String[] args) throws Exception
{
try
{
DataInputStream s=new DataInputStream(System.in);
Boolean IsWhile=true;
while(IsWhile)
{
System.out.println(“Enter the Cholice”);
System.out.println(“1. Load”);
System.out.println(“2. Insert”);
System.out.println(“3. Update”);
System.out.println(“4. Delete”);
Integer i= Integer.valueOf( s.readLine());
SQLConnection c=new SQLConnection();
switch(i)
{
case 1:
c.Load();
break;
case 2:
System.out.println(“Enter the Name”);
c.pName=s.readLine();
System.out.println(“Enter the Phone Number:-”);
c.Phone=s.readLine();
c.Insert();
break;
case 3:
System.out.println(“Enter the ID”);
c.Id= Integer.valueOf(s.readLine());
System.out.println(“Enter the Name:-”);
c.pName=s.readLine();
System.out.println(“Enter the Phone Number:-”);
c.Phone=s.readLine();
c.Update();
break;
case 4:
System.out.println(“Enter the ID”);
c.Id= Integer.valueOf(s.readLine());
c.Delete();
break;
}
System.out.println(“Do You Wish To Continue:”);
if(s.readLine()==”N”)
{
IsWhile=false;
}
}
}
catch(Exception ex)
{
System.out.println(“Error :- “+ex.getMessage());
}
}
}
package phonedirectory;
import java.sql.*;
public class SQLConnection
{
public Connection cCon;
public String pName;
public String Phone;
public int Id;
public SQLConnection() throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String db=”jdbc:odbc:mdb”;
cCon=DriverManager.getConnection(db);
}
public void Update() throws Exception
{
String QueryString=”Update Phone Set PName=’”+ pName +”‘,PNumber=’”+ Phone +”‘
Where ID=”+ String.valueOf(Id) +””;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Delete() throws Exception
{
String QueryString=”Delete from Phone Where ID=”+ String.valueOf(Id) +””;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Insert() throws Exception
{
String QueryString=”Insert into Phone(PName,PNumber) values(‘”+ pName +”‘,’”+ Phone
+”‘)”;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Load() throws Exception
{
String QueryString=”Select * from Phone”;
ResultSet rs;
Statement cSta=cCon.createStatement();
cSta.execute(QueryString);
rs=cSta.getResultSet();
boolean IsPresent=rs.next();
if(!IsPresent)
{
System.out.println(“No Record Found”);
return;
}
System.out.println(“ID \tName \t Phone No”);
while(IsPresent)
{
System.out.println(rs.getString(3) +”\t”+rs.getString(1) +”\t”+rs.getString(2));
IsPresent=rs.next();
}
}
}
Output:
Q) WAP Set of overload methods power that returns x^n where n is Int and x may be
Int or Float.
PROGRAM:
import java.io.*;
class ovrld
{
public int fn(int x, int n)
{
for(int i=1;i<n;i++)
{
x=x*x;
}
return x;
}
public float fn (float x, int n)
{
for(int i=1;i<n;i++)
{
x=x*x;
}
return x;
}
public static void main(String [] args)
{
ovrld ol=new ovrld ();
System.out.println(“Integer Power- “+ol.fn(2,2));
System.out.println(“Float Power- “+ol.fn(2.5f,2));
}
}
Output:
Q) Simple Program To Demonstrate JDBC.
PROGRAM:
import java.io.*;
import java.sql.*;
public class dbc
{
public static void main(String[] args)
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String db=”jdbc:odbc:mdb”;
Connection con=DriverManager.getConnection(db,””,””);
Statement cSta= con.createStatement();
String QueryString=”Select * from Student”;
ResultSet rs;
cSta.execute(QueryString);
rs=cSta.getResultSet();
while(rs.next())
{
System.out.println(rs.getString(“SName”));
}
String QueryString=”Insert into Student values(?,?,?,?)”;
PreparedStatement cSta1=
con.prepareStatement(QueryString);
cSta1.setInt(1,5);
cSta1.setString(1,”3″);
cSta1.setString(2,”Viraj”);
cSta1.setString(3,”Panvel”);
cSta1.setInt(4,100);
cSta1.executeUpdate();
System.out.println(“Data Inserted”);
}
}
catch(Exception ex)
{
System.out.println(“Error :- “+ ex.getMessage());
}
}
}
Output:
Q) WAP which will create user defined packages for Maharshtra, AndraPradesh,
UttarPradesh. Create sub-packages Mumbai, Pune in Maharashtra which will have
CST station, SarasBaug as classes. Create sub-package Agra in Uttarpradesh which will
have a class Tajmahal. In Andhra Pradesh create class as Charminar.
PROGRAM:
package india;
import india.maharashtra.*;
import india.delhi.*;
import india.adp.*;
public class India {
public static void main(String[] args) {
pune p=new pune();
mumbai m=new mumbai();
haidrabad h=new haidrabad();
del d=new del();
}
}
package india.adp;
public class haidrabad
{
public haidrabad()
{
System.out.println(“chandminar”);
}
}
package india.delhi;
public class del {
public del()
{
System.out.println(“tajmahal”);
}
}
package india.maharashtra;
public class mumbai
{
public mumbai()
{
System.out.println(“Gate of india”);
}
}
package india.maharashtra;
public class pune {
public pune()
{
System.out.println(“sarasbag”);
}
}
OUTPUT:
Q)
PROGRAM:
package animals;
public interface animal_inf
{
public void eat();
public void travel();
}
package animals;
public class Main {
public static void main(String[] args) {
}
}
package animals;
public class mammals implements animal_inf
{
public void eat()
{
System.out.println(“mammal is eating”);
}
public void travel()
{
System.out.println(“mammal is traveling”);
}
}
import animals.*;
public class anim {
public static void main(String args[])
{
mammals m = new mammals();
m.eat();
m.travel();
}
}
OUTPUT:
Q)
PROGRAM:
package mypkg;
public class circle
{
public void area()
{
System.out.println(“Area of circle=>”+(3.14*2*2));
}
}
package mypkg;
public class rect
{
public void area()
{
System.out.println(“Area of rectangle=>”+(10*20));
}
}
package mypkg;
public class square
{
public void area()
{
System.out.println(“Area of square=>”+(10*10));
}
}
import mypkg.*;
public class eg
{
public static void main(String args[])
{
circle c=new circle();
c.area();
rect r=new rect();
r.area();
square s=new square();
s.area();
}
}
OUTPUT:
Q)
PROGRAM:
package MyPack;
class balance
{
int id,bal;
balance(int i,int b)
{
id=i;
bal=b;
}
void show()
{
System.out.println(“ID=>”+id);
System.out.println(“BALANCE=>”+bal);
}
}
class accbalance
{
public static void main(String[] args)
{
balance b[]=new balance[3];
b[0]=new balance(1,1000);
b[1]=new balance(2,12000);
b[2]=new balance(3,10500);
for(int i=0;i<3;i++)
{
b[i].show();
}
}
}
package mypack;
class balance
{
sting name;
double bal;
}
balance (string m, double b)
{
name=m;
bal=b;
}
void show()
{
if(bal<100)
System.out.println(“—–LESS THAN 100>”);
else
System.out.println(“GREATER THAN 100″);
}
}
class account balance
{
public static void main(string args[])
{
Balance b=new balance["tushar",123];
b.show()
}
}
package mypack;
class balance
{
String name;
double bal;
balance(String m,double b)
{
name=m;
bal=b;
}
void show()
{
if(bal<100)
System.out.println(“—–LESS THAN 100>”);
else
System.out.println(“GREATER THAN 100″);
}
}
class account_balance
{
public static void main(String args[])
{
balance b=new balance(“tushar”,123);
b.show();
}
}
) Write a Program on jdbc to store telephone directory implement all operation
PROGRAM:
package phonedirectory;
import java.awt.Choice;
import java.io.DataInputStream;
public class PhoneDirectory
{
public static void main(String[] args) throws Exception
{
try
{
DataInputStream s=new DataInputStream(System.in);
Boolean IsWhile=true;
while(IsWhile)
{
System.out.println(“Enter the Cholice”);
System.out.println(“1. Load”);
System.out.println(“2. Insert”);
System.out.println(“3. Update”);
System.out.println(“4. Delete”);
Integer i= Integer.valueOf( s.readLine());
SQLConnection c=new SQLConnection();
switch(i)
{
case 1:
c.Load();
break;
case 2:
System.out.println(“Enter the Name”);
c.pName=s.readLine();
System.out.println(“Enter the Phone Number:-”);
c.Phone=s.readLine();
c.Insert();
break;
case 3:
System.out.println(“Enter the ID”);
c.Id= Integer.valueOf(s.readLine());
System.out.println(“Enter the Name:-”);
c.pName=s.readLine();
System.out.println(“Enter the Phone Number:-”);
c.Phone=s.readLine();
c.Update();
break;
case 4:
System.out.println(“Enter the ID”);
c.Id= Integer.valueOf(s.readLine());
c.Delete();
break;
}
System.out.println(“Do You Wish To Continue:”);
if(s.readLine()==”N”)
{
IsWhile=false;
}
}
}
catch(Exception ex)
{
System.out.println(“Error :- “+ex.getMessage());
}
}
}
package phonedirectory;
import java.sql.*;
public class SQLConnection
{
public Connection cCon;
public String pName;
public String Phone;
public int Id;
public SQLConnection() throws Exception
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String db=”jdbc:odbc:mdb”;
cCon=DriverManager.getConnection(db);
}
public void Update() throws Exception
{
String QueryString=”Update Phone Set PName=’”+ pName +”‘,PNumber=’”+ Phone +”‘
Where ID=”+ String.valueOf(Id) +””;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Delete() throws Exception
{
String QueryString=”Delete from Phone Where ID=”+ String.valueOf(Id) +””;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Insert() throws Exception
{
String QueryString=”Insert into Phone(PName,PNumber) values(‘”+ pName +”‘,’”+ Phone
+”‘)”;
Statement cSta=cCon.createStatement();
cSta.executeUpdate(QueryString);
cCon.close();
}
public void Load() throws Exception
{
String QueryString=”Select * from Phone”;
ResultSet rs;
Statement cSta=cCon.createStatement();
cSta.execute(QueryString);
rs=cSta.getResultSet();
boolean IsPresent=rs.next();
if(!IsPresent)
{
System.out.println(“No Record Found”);
return;
}
System.out.println(“ID \tName \t Phone No”);
while(IsPresent)
{
System.out.println(rs.getString(3) +”\t”+rs.getString(1) +”\t”+rs.getString(2));
IsPresent=rs.next();
}
}
}
Output:
Q) WAP Set of overload methods power that returns x^n where n is Int and x may be
Int or Float.
PROGRAM:
import java.io.*;
class ovrld
{
public int fn(int x, int n)
{
for(int i=1;i<n;i++)
{
x=x*x;
}
return x;
}
public float fn (float x, int n)
{
for(int i=1;i<n;i++)
{
x=x*x;
}
return x;
}
public static void main(String [] args)
{
ovrld ol=new ovrld ();
System.out.println(“Integer Power- “+ol.fn(2,2));
System.out.println(“Float Power- “+ol.fn(2.5f,2));
}
}
Output:
Q) Simple Program To Demonstrate JDBC.
PROGRAM:
import java.io.*;
import java.sql.*;
public class dbc
{
public static void main(String[] args)
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
String db=”jdbc:odbc:mdb”;
Connection con=DriverManager.getConnection(db,””,””);
Statement cSta= con.createStatement();
String QueryString=”Select * from Student”;
ResultSet rs;
cSta.execute(QueryString);
rs=cSta.getResultSet();
while(rs.next())
{
System.out.println(rs.getString(“SName”));
}
String QueryString=”Insert into Student values(?,?,?,?)”;
PreparedStatement cSta1=
con.prepareStatement(QueryString);
cSta1.setInt(1,5);
cSta1.setString(1,”3″);
cSta1.setString(2,”Viraj”);
cSta1.setString(3,”Panvel”);
cSta1.setInt(4,100);
cSta1.executeUpdate();
System.out.println(“Data Inserted”);
}
}
catch(Exception ex)
{
System.out.println(“Error :- “+ ex.getMessage());
}
}
}
Output:
Q) WAP which will create user defined packages for Maharshtra, AndraPradesh,
UttarPradesh. Create sub-packages Mumbai, Pune in Maharashtra which will have
CST station, SarasBaug as classes. Create sub-package Agra in Uttarpradesh which will
have a class Tajmahal. In Andhra Pradesh create class as Charminar.
PROGRAM:
package india;
import india.maharashtra.*;
import india.delhi.*;
import india.adp.*;
public class India {
public static void main(String[] args) {
pune p=new pune();
mumbai m=new mumbai();
haidrabad h=new haidrabad();
del d=new del();
}
}
package india.adp;
public class haidrabad
{
public haidrabad()
{
System.out.println(“chandminar”);
}
}
package india.delhi;
public class del {
public del()
{
System.out.println(“tajmahal”);
}
}
package india.maharashtra;
public class mumbai
{
public mumbai()
{
System.out.println(“Gate of india”);
}
}
package india.maharashtra;
public class pune {
public pune()
{
System.out.println(“sarasbag”);
}
}
OUTPUT:
Q)
PROGRAM:
package animals;
public interface animal_inf
{
public void eat();
public void travel();
}
package animals;
public class Main {
public static void main(String[] args) {
}
}
package animals;
public class mammals implements animal_inf
{
public void eat()
{
System.out.println(“mammal is eating”);
}
public void travel()
{
System.out.println(“mammal is traveling”);
}
}
import animals.*;
public class anim {
public static void main(String args[])
{
mammals m = new mammals();
m.eat();
m.travel();
}
}
OUTPUT:
Q)
PROGRAM:
package mypkg;
public class circle
{
public void area()
{
System.out.println(“Area of circle=>”+(3.14*2*2));
}
}
package mypkg;
public class rect
{
public void area()
{
System.out.println(“Area of rectangle=>”+(10*20));
}
}
package mypkg;
public class square
{
public void area()
{
System.out.println(“Area of square=>”+(10*10));
}
}
import mypkg.*;
public class eg
{
public static void main(String args[])
{
circle c=new circle();
c.area();
rect r=new rect();
r.area();
square s=new square();
s.area();
}
}
OUTPUT:
Q)
PROGRAM:
package MyPack;
class balance
{
int id,bal;
balance(int i,int b)
{
id=i;
bal=b;
}
void show()
{
System.out.println(“ID=>”+id);
System.out.println(“BALANCE=>”+bal);
}
}
class accbalance
{
public static void main(String[] args)
{
balance b[]=new balance[3];
b[0]=new balance(1,1000);
b[1]=new balance(2,12000);
b[2]=new balance(3,10500);
for(int i=0;i<3;i++)
{
b[i].show();
}
}
}
package mypack;
class balance
{
sting name;
double bal;
}
balance (string m, double b)
{
name=m;
bal=b;
}
void show()
{
if(bal<100)
System.out.println(“—–LESS THAN 100>”);
else
System.out.println(“GREATER THAN 100″);
}
}
class account balance
{
public static void main(string args[])
{
Balance b=new balance["tushar",123];
b.show()
}
}
package mypack;
class balance
{
String name;
double bal;
balance(String m,double b)
{
name=m;
bal=b;
}
void show()
{
if(bal<100)
System.out.println(“—–LESS THAN 100>”);
else
System.out.println(“GREATER THAN 100″);
}
}
class account_balance
{
public static void main(String args[])
{
balance b=new balance(“tushar”,123);
b.show();
}
}
ADTA
—————————————-Nested Table———————————1. Create a table customer with the attributes c_id, C_name and c_add. one customer can
have more then one address
the address field consist of street, city and state store the address as a nested table.
a] Create object ————–
create type add_type as object
(
street varchar2(10),
city varchar2(10),
state varchar2(10)
);
b]create nersted table————create type cadd_list as table of add_type;
c]Create oparent table————create table new_customer1
(
c_id number(5),
c_name varchar(10),
addres cadd_list
) nested table addres store as c_add;
d] Insert data into table————–>insert into new_customer1 values(1,’Nil’,cadd_list(add_type(‘Ashadh’,’Panvel’,’Maha’)));
–>insert into new_customer1 values(2,’Prajakta’,cadd_list
(add_type(‘Ashadh’,’Panvel’,’Maha’),
add_type(‘Anand’,’Dombiwali’,’Maha’)));
–>insert into new_customer1 values(
3,’Sneha’,cadd_list(add_type(‘Gandhi’,’Ahamadabad’,’Gijrat’),add_type(‘Sabarmati’,’Surat’
,’Gujrat’),add_type(‘Pushkar’,’Jaipur’,’Rajastan’)));
–>insert into new_customer1 values(4,’Priya’,cadd_list(add_type(‘IT
Colony’,’CBD’,’Maha’)));
–>insert into new_customer1
values(5,’Shreya’,cadd_list(add_type(‘VIP’,’Chembur’,’Maha’)));
–>insert into new_customer1
values(6,’Shruti’,cadd_list(add_type(‘VIP’,’Mumbai’,’Maha’)));
1. Display all the add details of all the customers.
—->select c_id,c_name,V.* from new_customer1, table(new_customer1.addres)v;
2. Display all the address details of customers hows city is mumbai.
—-> select c_id,c_name, V.* from new_customer1, table(new_customer1.addres)v where
city=’Mumbai’;
3. Display Customer id and c_name of all the customers if they have more than one address
in the table.
—-> select c_id,c_name from new_customer1, table(new_customer1.addres)v group by
c_id,c_name having count(c_id)>1;
4. Display the c_id and number of addresses stored in the table for each cutomer.
—-> select c_id,c_name, count(c_id) as Number_of_addresses from new_customer1,
table(new_customer1.addres)v group by c_id,c_name;
———————————————–Methods(Member Function)——————————
———————–
1. Create an object table contacts with the attributes name and ph_no.Also write a member
function to display the area code of the person.
a]. Create object
create or replace type person_type as object
(
p_name varchar2(10),
ph_no number(11),
member function getAreaCode Return varchar
);
b] Function Type Body Creation
create or replace type body person_type as
member function getAreaCode Return varchar is
Begin
return substr(ph_no,1,3);
End getAreaCode;
End;
c] Creat Object table
create table contacts of person_type;
d] Insert Values in boject table.
insert into contacts values(‘Nil’,0226892156);
insert into contacts values(‘Prajakta’,0215964586);
insert into contacts values(‘Priya’,2566985236);
insert into contacts values(‘Sys’,8569865985);
insert into contacts values(‘Nidhi’,0224568936);
1. Display the name and phone number from the table whos name starts with ‘A’
—> select * from contacts where p_name like ‘N%’;
select v(s).p_name, v(s).ph_no from contacts s where v(s).p_name like ‘N%’;
2. Display the name and AreaCode of all the person.
—> select c.p_name, c.getAreaCode() from contacts c ;
—————————————————————————————————————
————————————————————————————
2. Create a table books with the attributes b_id, b_name and price.Also create a member
function to calculate the final book price after giving a discount.
a] Create object (name, prcie and member function)
create or replace type book_type as object
(
b_name varchar2(10),
price number(5),
member function getBookPrice(discount number) Return number
);
b] Function body
create or replace type body book_type as
member function getBookPrice(discount number) Return number is Book_price number;
Begin
select (price – (price * discount/100)) Into Book_price from Dual;
return book_price;
End;
End;
c] Creat table
create table book
(
b_id number(2),
book_info book_type
);
d] Insert data into table
insert into book values(1,book_type(‘Java’,500));
insert into book values(2,book_type(‘Cpp’,100));
insert into book values(3,book_type(‘JavaScript’,300));
insert into book values(4,book_type(‘HTML’,50));
insert into book values(5,book_type(‘C#’,350));
1. Display the book detailes if the proce is greater than 150.
—> select c.book_info.b_name from book c where c.book_info.price>150;
2. Display the name, price and the final price after giving a discount of 5%.
—>select c.book_info.b_name,c.book_info.price as Og_price,c.book_info.getBookPrice(10)
As Price_After_Discount from book c;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
VARRAY AND TABLE PARTITIONING
create or replace type type_name1 as object
(fname varchar(20),
mname varchar(20),
lname varchar(20)
);
/
create or replace type type_address as object
(streat varchar(20),
city varchar(20),
pincode number(10)
);
/
***** create table
create table customer
(
c_id number(5) primary key,
c_name type_name,
c_add type_address,
c_phno number(10)
);
***** insert Data
insert into customer values(1, type_name(‘vijaY’, ‘s’, ‘sargar’),
type_address(‘snagar’,’mumbai’,’416410′),06873045);
insert into customer values(2, type_name(‘Shreyas’, ‘H’, ‘pednekar’),
type_address(‘Govandi’,’mumbai’,’413410′),06872345);
insert into customer values(3, type_name(‘Nikhil’, ‘R’, ‘Dhimate’),
type_address(‘Govandi’,’mumbai’,’413410′),06872345);
insert into customer values(4, type_name(‘Nitin’, ‘R’, ‘Matekar’),
type_address(‘nerul’,’sangli’,’413410′),98789787);
insert into customer values(5, type_name(‘Sagar ‘, ‘ R ‘, ‘ Salvi’),
type_address(‘Thane’,’Thane’,’876553′),93425587);
set describe depth 2,
describe customer
Q….display the street name of customer with id 2..
-> select c.c_add.street from customer c where c_id=2;
Q….display the details of customer who all from Mumbai..
-> select * from customer c where c.c_add.city=’mumbai’ and c.c_name.fname=’Shreyas’;
Q….Display the name of all customers
-> select c.c_name.fname ||”|| c.c_name.mname ||”|| c.c_name.lname as name from customer
c;
Q….create one object with rno and name
-> create or replace type student_type as object
(
roll_num number(20),
name varchar(20)
);
create table student of Student_type;
insert into student values(student_type(1,’Nilima’));
insert into student values(student_type(2,’Priyanka’));
insert into student values(student_type(3,’Nitin’));
insert into student values(student_type(4,’Sys’));
insert into student values(student_type(5,’Vijay’));
insert into student values(student_type(6,’Prajakta’));
insert into student values(student_type(7,’Aditi’));
Q… disp name of all student whos rno is less than 10
-> select * from student s where roll_num < 3;
-> where s.roll_num<5;
-> select value(s).name from student s where s.roll_num<5;
************ Altering the object Type **************
alter type student_type add attribute(course varchar2(5), feepaid number(5)) cascade;
select * from student;
update table student set course=’MCA’ and feespaid=100000 where roll_num=’2′;
add a member function get fee to the existing student_type
*******************VARRAY*****************************
creTE A TABLE EMP with the info emp_num,emp_name,dept_id,projects.one emp can is
having multiple projects.
1.create varry for stoting the projects.
2.create type project_list as varray(10) of varchar(100);
create table employee
(
eno number(5),
ename varchar(10),
deptno number(5),
projects project_list);
3.Insert valuse in Table Employee.
insert into employee
values(1,’Nil’,102,project_list(‘Banking’,’library’,’pizzahut’,’cantinmgmt’));
insert into employee
values(2,’Priya’,104,project_list(‘BloodBanking’,’Inventory’,’Subway’,’hotelmgmt’));
insert into employee
values(1,’Sys’,106,project_list(‘Calci’,’mathguid’,’magdi’,’hospitalmgmt’));
Q……..4.display all the projects undertaken by the emp with eno ’1′.
select column_value as Project_Name from employee, table(employee.projects)v where
eno=2;
//select v.* as Project_Name from employee, table(employee.projects)v where eno=2;
select projects from employee where eno=2;
————Modifing the Varray contents———1. change the project list of employee with eno=2 as banking,education and aviation
update employee set projects=project_list(‘banking’,’education’,’aviation’) where eno=2;
———— Varray and Object ——————1. creat a table employee with information eno, ename, dept_id and projects.
one employee can undertake more thanone project. A Project is having p_id, p_name and
cost.
create type proj_type as object
(
pid number(3),
pname varchar2(10),
pcost number
);
create type proj_list as varray(10) of proj_type;
create table emp_det
(
eno number(5),
ename varchar(10),
deptno number(5),
projects proj_list
);
insert into emp_det values(1,’Nil’,102,proj_list(proj_type(1,’Banking’,5000)));
insert into emp_det
values(4,’Praj’,106,proj_list(proj_type(1,’Banking’,5000),proj_type(6,’Education’,25000)));
insert into emp_det
values(2,’Priya’,104,proj_list(proj_type(4,’Aviation’,500000),proj_type(6,’Education’,25000
)));
Display project name and cost of projects undertaken by employee with eno=3
—> select V.* from emp_det, table(emp_det.projects)v where eno=2;
disply allthe project detailes of all the employee
—> select V.* from emp_det, table(emp_det.projects)v
Display project name and cost of projects undertaken by employee with eno=3
—> select V.pname,v.pcost from emp_det, table(emp_det.projects)v where eno=4;
create table student with information roll_no, fname, lname, street, city, pincode and activity
one student can participate in more than one activity.each activity has details a_id,
a_name.Implement this using Varray.
—->
create type act_type as object
(
a_id number(3),
a_name varchar2(10)
);
create type name_type as object
(
fname varchar2(10),
lname varchar2(10)
);
create type add_type as object
(
street varchar2(10),
city varchar2(10),
pincode number(6)
);
create type act_list as varray(10) of act_type;
create table stud_det
(
roll_no number(5),
name name_type,
addr add_type,
activity act_list
);
insert into stud_det values
(
1,
name_type(‘Nilima’,’Chaudhari’),
add_type(‘Adshadh’,’Panvel’,410206),
act_list(act_type(10,’reading’))
);
insert into stud_det values
(
2,
name_type(‘Prajakta’,’Chaudhari’),
add_type(‘Adshadh’,’Panvel’,410206),
act_list(act_type(11,’writing’),act_type(10,’reading’))
);
insert into stud_det values
(
3,
name_type(‘Priyanka’,’Dange’),
add_type(‘IT_colony’,’Belapur’,411523),
act_list(act_type(09,’talking’),act_type(11,’writing’),act_type(10,’reading’))
);
insert into stud_det values
(
4,
name_type(‘Shrey’,’Pednekar’),
add_type(‘Sys’,’Chembur’,415253),
act_list(act_type(08,’Program’),act_type(15,’Sports’))
);
1. disply rollno, name and add of all students
—-> select roll_no, s.name.fname||’ ‘||s.name.lname as Name, s.addr.street||’ ‘||s.addr.city as
Address from stud_det s ;
2. Disply activity of all the students
—-> select V.* from stud_det, table(stud_det.activity)v;
3. Display roll_no and fname of activity of the students who are participating in more than
one activity.
—->select roll_no,s.name.fname from stud_det s, table(s.activity) group by
s.roll_no,s.name.fname having count(*) >1;
4.Display city, name of activity and activity count of all the students.
—>select roll_no,s.name.fname Name,count(*) from stud_det s, table(s.activity) group by
s.roll_no;
**************************Partitioning the excisting
Table:***************************************
1. create a non-partition table student with the fields roll_no, name, mark and insert records in
it.
create table Stud_det1
(
roll_no number(5) primary key,
name varchar(10),
marks number
);
insert into stud_det1 values(1,’Nilima’,40);
insert into stud_det1 values(2,’Praju’,55);
insert into stud_det1 values(3,’Adi’,61);
insert into stud_det1 values(4,’Priya’,82);
insert into stud_det1 values(5,’Sneh’,75);
insert into stud_det1 values(6,’Patil’,61);
insert into stud_det1 values(7,’Pradnya’,82);
2. create a table with one partition which will act as a destination table with tha same fildes as
a source table.
create table stud_det1_dest
(
roll_no number(5) primary key,
name varchar(10),
marks number
)
partition by range (roll_no) ( partition p1 values less than (maxvalue) tablespace users) ;
3.switch the orignal table segment with partition segment
alter table stud_det1_dest exchange partition p1 with table stud_det1 without validation;
Display records from both table.
select * from stud_det1_dest ;
select * from stud_det1;
4. Drop orignal table and rename the partitioned table.
drop table stud_det1;
alter table stud_det1_dest rename to stud_det1;
5. Split the partition table with multiple partitions as needed.
alter table stud_det1 split partition p1 at(1) into(partition p2, partition p3);
select * from stud_det1 partition(p2) ;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Inheritance, overriding
create type person_type as object
(
name varchar2(10),
ph_no number(10)
);
create table contact_table
(
contact ref person_type,
cdate date
);
create table person_table of person_type;
insert into person_table values(person_type(‘Priya’,9687965895));
insert into person_table values(person_type(‘Nil’,9856985478));
insert into person_table values(person_type(‘Shreya’,9863256975));
insert into person_table values(person_type(‘Praju’,9758624569));
1) insert only the contact detailes where thw name start with V
2) insert into contact_table select ref(p),’1-mar-2014′ from person_table p where p.name
like ‘P%’;
select deref(contact).name,cdate from contact_table;
select c.contact.name,c.cdate from contact_table c;
————————————————————————————–
———————Overriding————Overloading——————————
create a type type_A with the attributes eid and the member function finddata(), which
returns
eid.create another type type_B with attribute a, b and c and override the above member
function
to display sum of a, b and c.
create or replace type type_A as object
(
eid number,
member function finddata return number
)
not final;
create or replace type body type_a as
member function finddata Return number is
Begin
return eid;
End finddata;
End;
create or replace type type_B under type_A
(
a number,
b number,
c number,
overriding member function finddata return number
)
not final;
create or replace type body type_b as
overriding member function finddata Return number is
Begin
return a+b+c;
End finddata;
End;
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
->Create a type Person_type with the attributes name, address, age and a member function
toString().Create another type student_type with the attributes course , balance and a member
function payment () to display the balance. Also override tostring() member function to
display name, age and balance of the students.
Step1:type person_type
Create type person3_type as object
(name varchar(20),address varchar(20),age number, Member function tostring return varchar)
not final;
Type created.
Step2:Define the body of the function.
Create type body person3_type as
Member function tostring return varchar is
Begin
If age <= 10 then
return ‘Child’;
elsIf age = 18 then
return ‘teenager’;
End if;
End tostring;
End;
/ Type body created.
Step3:type student_type
Create type student1_type under person3_type
(course varchar(20),balance number, Member function payment return number, overriding
member function tostring return varchar);
Type created.
Step4:Define the body of the function.
Create or replace type body student1_type as
Member function payment return number is
Begin
Return balance;
End payment;
overriding Member function tostring return varchar is
Begin
Return name;
End tostring;
End;
/ Type body created.
Invoking using PLSql
Declare
P person_type;
S student_type;
Begin
P:=person_type(values);
S:=student_type(values);
Dbms_output.put_line(s.tostring);
Dbms_output.Put_line(p.tostring);
Implementation of Overloading
->Create a type emp_type with the attributes emp_no, name, basic_salary and two member
functions getSalary().The first member function doesnot take any argument and returns a
basic pay.The second member function pass the number of days as the argument and return
the salary based on the number of days.
Step1:type emp_type
Create or replace type emp1_type as object
(emp_no number, name varchar(20), basic_salary number, Member function getSalary return
number, Member function getSalary(s number) return number);
Type created.
Step2:Define the body of the function.
Create or replace type body emp1_type as
Member function getSalary return number is
Begin
Return basic_salary;
End getSalary;
Member function getSalary(s number) return number is
Begin
Return (basic_salary*s)/30;
End getSalary;
End;
Type body created.
Invoking the member function using PLSQL
Declare
E emp1_type;
Begin
E:=emp1_type(1001,’Alice’,2000);
Dbms_output.put_line(e.getSalary());
Dbms_output.put_line(e.getSalary(5));
End;
2000
333.333333333333333333333333333333333333
Create table emp_tbl of emp1_type;
Table created.
Insert into emp_tbl values(1002‘Pravin’,2000);
Insert into emp_tbl values(1003,‘Nilesh’,2000);
Insert into emp_tbl values(1004,‘Prashant’,2000);
Insert into emp_tbl values(1005,‘Ram’,2000);
Select value(emp).rollno as Roll_no, value(s).name.fname as Name, s.getfee() as
Total_fees from emp_tbl emp;
SQL> Select value(emp).emp_no as emp_no, value(emp).name as Name, emp.getSalary(5)
as Total_salary from emp_tbl emp;
++++++++++++++++++++++++++++++++++++++++++++++++++++++
—————————————–OLAP————————————-
Sales Table:
Cerate a table sales with the attribute (did number(3), dept_name varchar(10), d_year date(),
region varchar(10), profit number (3))
create table sales_1
(d_id number(3),
dept_name varchar(10),
d_year number(4),
region varchar(10),
profit number (3));
Insert data:
insert into sales_1 values(1,’Market’,1991,’Mumbai’,100);
insert into sales_1 values(1,’Market’,1992,’Mumbai’,155);
insert into sales_1 values(1,’Market’,1991,’Chennai’,111);
insert into sales_1 values(1,’Market’,1992,’Chennai’,101);
insert into sales_1 values(2,’Purchase’,1991,’Mumbai’,500);
insert into sales_1 values(2,’ Purchase’,1992,’Mumbai’,55);
insert into sales_1 values(2,’ Purchase’,1991,’Chennai’,120);
insert into sales_1 values(2,’ Purchase’,1992,’Chennai’,320);
insert into sales_1 values(1,’Market’,1993,’Mumbai’,180);
insert into sales_1 values(1,’Market’,1993,’Chennai’,300);
insert into sales_1 values(2,’Purchase’,1993,’Mumbai’,525);
insert into sales_1 values(2,’ Purchase’,1993,’Chennai’,320);
Select * from sales_1;
D_ID DEPT_NAME D_YEAR REGION PROFIT
—— ———- ———- ———- ———1 Market 1991 Mumbai 100
1 Market 1992 Mumbai 155
1 Market 1991 Chennai 111
1 Market 1992 Chennai 101
2 Purchase 1991 Mumbai 500
2 Purchase 1992 Mumbai 55
2 Purchase 1991 Chennai 120
2 Purchase 1992 Chennai 320
1 Market 1993 Mumbai 180
1 Market 1993 Chennai 250
2 Purchase 1993 Mumbai 525
D_ID DEPT_NAME D_YEAR REGION PROFIT
—— ———- ———- ———- ———2 Purchase 1993 Chennai 320
—————————————-OLAP Analytical Functions——————————–
1. Select from table with roe number:
Select rownum,d_id,dept_name,profit from sales_1;
2. Arrange roes according to prifit
Select rownum,d_id,dept_name,profit from sales_1 order by profit;
———————————————————-RollUP———————————————
————
3. Display year wise total profit.
a. Select d_year,sum(profit) from sales_1 group by rollup(d_year);
D_YEAR SUM(PROFIT)
——– ———–
1991 831
1992 631
1993 1275
2737
b.Select d_year,sum(profit) from sales_1 group by d_year;
D_YEAR SUM(PROFIT)
——– ———–
1991 831
1992 631
1993 1275
4. Display year wise total profit of each region :
a. Select region,d_year,sum(profit) from sales_1 group by rollup(d_year,region);
REGION D_YEAR SUM(PROFIT)
———- ———- ———–
Mumbai 1991 600
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Windowing Clause
Create a table emp with the attributes (eno,ename,dept_name,salary)
Create table emp_1
(e_id number(10),
e_name varchar(10),
dept_name varchar(10),
salary number);
Inset values in emp_1:
insert into emp_1 values(1,’Nil’,’IT’,10000);
insert into emp_1 values(2,’Aditi’,’IT’,10220);
insert into emp_1 values(3,’Priyal’,’IT’,10000);
insert into emp_1 values(4,’Shreyal’,’IT’,15000);
insert into emp_1 values(13,’Suman’,’IT’,18000);
insert into emp_1 values(5,’Vaibhav’,’Market’,15500);
insert into emp_1 values(6,’Nisha’,’Market’,15500);
insert into emp_1 values(7,’Komal’,’Market’,12200);
insert into emp_1 values(8,’Kashmira’,’Market’,15000);
insert into emp_1 values(9,’Sneh’,’HR’,18000);
insert into emp_1 values(10,’Praju’,’HR’,20000);
insert into emp_1 values(11,’Parth’,’HR’,18000);
insert into emp_1 values(12,’Teju’,’HR’,20200);
select * from emp_1;
E_ID E_NAME DEPT_NAME SALARY
1 Nil IT 10000
2 Aditi IT 10220
3 Priyal IT 10000
4 Shreyal IT 15000
13 Suman IT 18000
5 Vaibhav Market 15500
6 Nisha Market 15500
7 Komal Market 12200
8 Kashmira Market 15000
9 Sneh HR 18000
10 Praju HR 20000
11 Parth HR 18000
12 Teju HR 20200
1. Display eno, ename, dept_name, salary and dept wise sum of salary of current and
previous 2 records:
Select e_id,e_name,dept_name,salary,sum(salary) over(partition by dept_name order by
dept_name rows 2 preceding ) total from emp_1 order by dept_name;
E_ID E_NAME DEPT_NAME SALARY TOTAL
9 Sneh HR 18000 18000
10 Praju HR 20000 38000
12 Teju HR 20200 58200
11 Parth HR 18000 58200
1 Nil IT 10000 10000
2 Aditi IT 10220 20220
3 Priyal IT 10000 30220
4 Shreyal IT 15000 35220
13 Suman IT 18000 43000
5 Vaibhav Market 15500 15500
6 Nisha Market 15500 31000
7 Komal Market 12200 43200
8 Kashmira Market 15000 42700
2. Display eno, ename, dept_name, salary and dept wise sum of salary of current and
previous 3 records and next 1 record:
Select e_id,e_name,dept_name,salary,sum(salary) over (partition by dept_name order by
dept_name rows between 3 preceding and 1 following)Total from emp_1 order by
dept_name;
E_ID E_NAME DEPT_NAME SALARY TOTAL
9 Sneh HR 18000 38000
10 Praju HR 20000 58200
12 Teju HR 20200 76200
11 Parth HR 18000 76200
1 Nil IT 10000 20220
2 Aditi IT 10220 30220
3 Priyal IT 10000 45220
4 Shreyal IT 15000 63220
13 Suman IT 18000 53220
5 Vaibhav Market 15500 31000
6 Nisha Market 15500 43200
7 Komal Market 12200 58200
8 Kashmira Market 15000 58200
3. Display eno, ename, dept_name, salary and and dept wise sum of salary for all the
preceding rows and the current row:
Select e_id,e_name,dept_name,salary,sum(salary) over (partition by dept_name order by
salary rows between unbounded preceding and current row)Total from emp_1 order by
dept_name;
E_ID E_NAME DEPT_NAME SALARY TOTAL
9 Sneh HR 18000 18000
11 Parth HR 18000 36000
10 Praju HR 20000 56000
12 Teju HR 20200 76200
1 Nil IT 10000 10000
3 Priyal IT 10000 20000
2 Aditi IT 10220 30220
4 Shreyal IT 15000 45220
13 Suman IT 18000 63220
7 Komal Market 12200 12200
8 Kashmira Market 15000 27200
5 Vaibhav Market 15500 42700
6 Nisha Market 15500 58200
——————CASE Equation ——————1. Write a query to finding if the salary is greater than 9000.
Select case when e.salary > 12000 then e.salary else 12000 end as Case from emp_1 e;
2. Write a query to find the avg of salary if the salary is < 10000 , then consider it as 9000;
Select case when e.salary > 12000 then e.salary else 12000 end as AVG from emp_1 e;
3. Find the avg of all the emp (consider only those emp whose salary is < 11000)
Select case when e.salary < 11000 then e.salary else Null end as AVG from emp_1 e;
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ETL Steps:
step-1
a] Create table sales_record
create table sales_record
(
s_name varchar2(10),
item_sold varchar2(15),
price number(5),
sdate date,
item_cat varchar2(10),
no_of_item_sold number(3)
);
insert into sales_record values(‘Nil’,’Notebook’,20,’12-Feb-2014′,’Sationary’,10);
insert into sales_record values(‘Joshi’,’Book’,500,’13-March-2014′,’Sationary’,30);
insert into sales_record values(‘Sneh’,’Projector’,10,’10-Feb-2014′,’Hardware’,10);
insert into sales_record values(‘Kashmira’,’Book’,100,’13-March-2014′,’Sationary’,30);
insert into sales_record values(‘Krishna’,’Notebook’,50,’10-Feb-2014′,’Sationary’,5);
insert into sales_record values(‘Joshi’,’Book’,500,’13-March-2014′,’Sationary’,30);
b] Create table sales_detailes
create table sales_detailes
(
sales_person varchar2(10),
item_name varchar(15),
item_price number(5),
sdate date,
branch varchar2(10),
no_of_item_sold number(3)
);
insert into sales_detailes values(‘Nil’,’Notebook’,20,’12-Feb-2014′,’Mumbai’,10);
insert into sales_detailes values(‘Joshi’,’Book’,500,’13-March-2014′,’Pune’,30);
insert into sales_detailes values(‘Sneh’,’Projector’,10,’10-Feb-2014′,’Ahmadabad’,10);
insert into sales_detailes values(‘Kashmira’,’Book’,100,’13-March-2014′,’Mumbai’,30);
insert into sales_detailes values(‘Krishna’,’Notebook’,50,’10-Feb-2014′,’Mumbai’,5);
step-2
Extract detailes from these sales_details and sales record into sales table.
create table sales
(
sales_person varchar2(10),
item_name varchar(15),
item_price number(5),
sdate date,
branch varchar2(10),
item_cat varchar2(10),
no_of_item_sold number(3)
);
Extract from sales_records:
insert into sales select s_name,item_sold,price,sdate,null,item_cat,no_of_item_sold from
sales_record;
Extract from sales_detailes:
insert into sales select sales_person,item_name,item_price,sdate,branch,null,no_of_item_sold
from sales_detailes ;
step-3
Transfer the data stored in sales & load it into sales-w
update sales set branch=’Pune’ where sales_person=’Joshi’;
update sales set branch=’Ahmadabad’ where sales_person=’Sneh’;
update sales set branch=’Mumbai’ where sales_person=’Kashmira’;
update sales set branch=’Mumbai’ where sales_person=’Krishna’;
update sales set branch=’Mumbai’ where sales_person=’Nil’;
update sales set branch=’Mumbai’ where sales_person=’Nil’ or sales_person=’Krishna’;
update sales set item_cat=’Sationary’ where sales_person=’Nil’ or sales_person=’Joshi’ or
sales_person=’Krishna’ or sales_person=’Kashmira’;
update sales set item_cat=’Hardware’ where sales_person=’Sneh’;
step-4
Loading data into sales_d_w.
create table sales_d_w as select * from sales;
step-5
Create Summary:
->create summary of sales_d_w;
->create or replace type type_sales as object (sname varchar2(20), item_sold
varchar2(20),price number(10), sdate date, branch varchar2(20), itemcat varchar2(20),
no_of_item_sold number);
Create view
->create view sales_view of type_sales with object sid(sname) as select s.sname, s.item_sold,
s.price, s.date, s.branch, s.no_of_item_sold from sales s;
++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Bitmap index & Execution Plan
In admin
1. Create this table in admin
SQL> @C:\oracle\ora92\rdbms\admin\utlxplan.sql
2. Open plustrce.sql file
Add one more line there
grant plustrace to scott with admin option;
Save that file
3. SQL> @C:\oracle\ora92\sqlplus\admin\plustrce.sql
Now connecc to scott
SQL> connect scott
Enter password: *****
Connected.
create a table customer with attribute (c_id number primary key, c_name varchar(10), gender
varchar2(1),address varchar(23))
create table customer_12
(c_id number primary key,
c_name varchar(10),
gender varchar2(1),
address varchar2(23));
insert into customer_12 values(101,’Nil’,’F’,’Panvel’);
insert into customer_12 values(102,’Sneh’,’M’,’Ahamadabad’);
insert into customer_12 values(103,’Praju’,’F’,’Navi Mumbai ’);
insert into customer_12 values(104,’Priyanka’,’F’,’Belapur’);
insert into customer_12 values(105,’Shrey’,’M’,’Chembur’);
insert into customer_12 values(106,’Nisha’,’F’,’Palghar’);
insert into customer_12 values(107,’Vaibhav’,’M’,’Nerul’);
insert into customer_12 values(108,’Aditi’,’F’,’Vashi ’);
insert into customer_12 values(109,’Priya’,’F’,’Nagpur’);
insert into customer_12 values(110,’Krish’,’M’,’Chennai’);
SQL> set autotrace on;
SQL> select * from stud;
SQL> create bitmap index cust_index on customer_12(gender);
Create table sales_12
(
S_id number,
Customer_id number(3),
P_name varchar2(20), P_price number(4),
primary key(S_id, Customer_id)
)
insert into sales_12 values(1001,102,’Book’,500);
insert into sales_12 values(1002,107,’Notebook’,50);
insert into sales_12 values(1003,105,’Pen’,5);
insert into sales_12 values(1004,110,’Dictionary’,110);
insert into sales_12 values(1005,112,’Book’,120);
insert into sales_12 values(1006,114,’Table_book’,10);
insert into sales_12 values(1007,105,’Pen’,30);
Creating Bitmap Index of sales and customer_12:
Create bitmap index sale_cust_index on sales_12(customer_12. gender) from sales_12,
customer_12 where sales_12. Customer_id= customer_12. c_id;
1. Display s_id,gender and price of all the customers who all purchased items.
Select s.s_id, c.gender, s. P_price from sales_12 s, customer_12 c where s. Customer_id= c.
c_id;
2. Display c_id,,c_name,gender,prod_id and price details of all curomers;
—————————Horizontal Fragmentation—————————–
Create a table emp_12 (e_no number, e_name varchar2(),e_add varchar(25),e_sal number(5)
)
Original table———Create table emp_12
(e_no number(3),
e_name varchar2(15),
e_add varchar2(25),
e_sal number(5) );
Fragment1————
Create table emp_hz1
(e_no number(3),
e_name varchar2(15),
e_add varchar2(25),
e_sal number(5) );
Fragment2————
Create table emp_hz2
(e_no number(3),
e_name varchar2(15),
e_add varchar2(25),
e_sal number(5) );
Create a trigger to insert data into emp_hz1 and emp_hz2 when data inserted into emp_12
table. The emp details should be stored in emp_hz1 if salary is less than 10000 and should be
inserted into emp_hz2 if salary is >= 10000.
Create or replace trigger emp_t
After insert on emp_12 for each row
When(new.e_sal is not null)
Begin
If :new.e_sal<10000 then
Insert into emp_hz1 values
(:new.e_no,:new.e_name,:new.e_add,:new.e_sal);
Else
Insert into emp_hz2 values
(:new.e_no,:new.e_name,:new.e_add,:new.e_sal);
End if;
End;
Inset Values:
Insert into emp_12 values(101,’Nil’,’Panvel’,9999);
Insert into emp_12 values(102,’Sneh’,’Ahamadabad’,20999);
Insert into emp_12 values(103,’Priyanka’,’Belapur’,15000);
Insert into emp_12 values(104,’Shrey’,’Chembur’,9998);
Select * from emp_12;
E_NO E_NAME E_ADD E_SAL
—– ————— ————————- ———101 Nil Panvel 9999
102 Sneh Ahamadabad 20999
103 Priyanka Belapur 15000
104 Shrey Chembur 9998
Select * from emp_hz1;
E_NO E_NAME E_ADD E_SAL
—- ————— ————————- ———101 Nil Panvel 9999
104 Shrey Chembur 9998
Select * from emp_hz2;
E_NO E_NAME E_ADD E_SAL
—- ————— ————————- ———102 Sneh Ahamadabad 20999
103 Priyanka Belapur 15000
—————————————– vertical fragmentation——————————————
create or replace trigger emp_t2
after insert on emp_12
for each row
begin
insert into emp_v1@link11 values(:new.e_id,:new.e_name,:new.e_add);
insert into emp_v2@link22 values(:new.e_id,:new.e_sal);
end;
—————–Trigger- Replication—————
create or replace Trigger insert_data
after insert on employee_replica
for each row
begin
insert into employee1_replica @link111
values (:new.eno, :new.ename, :new.address, :new.email, :new.salary);
Horizontal fragmentation
Create table employee
( Eno number,
Ename varchar2(10),
Address varchar2(20),
Salary number);
Create public database link link1 connect to user1 identified by *** using ‘orcl’;
Create public database link link2 connect to user2 identified by *** using ‘orcl’;
User1
Create table empHz1
( Eno number,
Ename varchar2(10),
Address varchar2(20),
Salary number);
User2
Create table empHz2
( Eno number,
Ename varchar2(10),
Address varchar2(20),
Salary number);
-
Trigger (to insert) –Horizontal fragmentation
create or replace trigger empt
after insert on employee
for each row
when(new.salary is not null)
begin
if :new.salary<10000 then
insert into emphz1 @link1values
(:new.eno,:new.ename,:new.address,:new.salary);
else
insert into emphz2 @link2values
(:new.eno,:new.ename,:new.address,:new.salary);
end if;
end;
In user1
select * from emphz1;
Select * from emphz2@link2;
In user2
select * from emphz2;
Select * from emphz1@link1;
*********************************
—————————————– vertical fragmentation——————————————
Vertical Fragment1————
Create table emp_vz1
(e_no number(3),
e_name varchar2(15),
e_add varchar2(25));
Vertical Fragment2————
Create table emp_vz2
(e_no number(3),
e_sal number(5) );
create or replace trigger emp_t2
after insert on emp_12
for each row
begin
insert into emp_vz1 values(:new.e_no,:new.e_name,:new.e_add);
insert into emp_vz2 values(:new.e_no,:new.e_sal);
end;
—————– Replication —————
Create Replica table of emp_12 ———Create table emp_12_replica
(e_no number(3),
e_name varchar2(15),
e_add varchar2(25),
e_sal number(5) );
Trigger for updating replication:
create or replace Trigger insert_data
after insert on emp_12
for each row
begin
insert into emp_12_replica
values(:new.e_no,:new.e_name,:new.e_add,:new.e_sal);
end;
Insert into emp_12 values(106,’Aditi’,’Mumbai’,35000);
Insert into emp_12 values(107,’Vaibhav’,’Chembur’,5000);
Insert into emp_12 values(108,’Parth’,’Pune’,35000);
Insert into emp_12 values(109,’Kaushik’,’Nagpur’,8000);
+++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++
Topic : Partitions
create table emp eid name salary
partition by hash
create table employee(eid varchar(10),ename varchar(30),
salary number) partition by hash(eid)(partition P1 tablespace users,
partition P2 tablespace users);
insert into employee values (’01′,’Pravin’,2200);
insert into employee values (’02′,’Sachin’,3200);
alter table employee add partition P3;
alter table employee truncate partition P3;
remove single partition and redristibute the data
alter table employee coalesce partition P3
//select table_name,partition_name from user_tab_partitions where
table_name=’EMPLOYEE’;
++++++++++++++++++++++++++++++++++++++++++++++++++++
Q1.
Explain term Partitions and different methods of partitioning?
Q2.
What is Tablespace? Show syntax for creating tablespace. Create 2
tablespace with name Cust and stud, size 5m each and save as datafile.
Q3.
Explain Range Partition. Create partition table Purchaser using range
partition on amtpaid column.
Date:
Purchaser(pur_id,pname,address,amtpaid,prod_pur).
Q4.
Insert Five records in Purchaser table.
Q5.
Display entire data in table and also display data partition wise.
Q6.
Split any one partition into two partitions and merge any two partitions into
one partition.
Q7.
Add a new partition.
Q8.
Drop an existing partition.
Q9.
Explain List Partition. Create partition table scholar using List partition on
city column.
scholar(sid,sname,address,city,per_of_marks,specialization).
Q10.
Insert Five records in scholar table.
Q11. Display entire data in table and display data partition wise.
Q12. Split any one partition into two partition and merge any two partition into
one partition.
Q13. Modify an existing partition
Q14. Add a new partition.
Q15. Truncate an existing partition.
Q16. Explain Hash Partition. Create partition table cabinet using Hash partition
oncidcolumn.cabinet(cid,mem_name,address,state_rep,phone_number).
Q17.
Insert Five records in cabinet table.
Q18. Display entire data in table and display data partition wise.
Q19. Explain Composite Partitioning.
Q20. Explain RangeHashComposite Partition. Create partition table product
using Range partition on price column and Hash subpartition on pdesc
column.Product(prod_no,pdesc,price).
Q21.
Insert Five records in Product table.
Q22. Display entire data in table and display data partition wise and subpartion
Q23. Explain RangeHash Partition. Create partition table Tax using Range
partition on taxamt column and List subpartition on state column.
Tax(dept_no,taxamt,state).
Q24.
Insert Five records in Tax table.
Q25. Display entire data in table and display data partition wise and subpartion
1.
Explain term Partitions and different methods of partitioning?
PARTITION
-Table partitioning is a data organization scheme in which table data is divided across
multiple storage objects called data partitions or ranges according to values in one or more
table columns.
-Each data partition is stored separately. These storage objects can be in different table
spaces, in the same table space, or a combination of both.
-Data warehouses often contain large tables and require techniques both for managing these
large tables and for providing good query performance across these large tables. This chapter
discusses partitioning, a key methodology for addressing these needs.
Different Methods of Partitioning:
PARTITIONING METHOD
BRIEF DESCRIPTION
Range Partitioning
Used when there are logical ranges of data.Possible usage:
dates, part numbers, and serial numbers.
Hash Partitioning
Used to spread data evenly over partitions.Possible usage: data
has no logical groupings.
List Partitioning
Used to list together unrelated data into partitions. Possible
usage: a number of states list partitioned into a region.
Used to range partition first, then spreads data into hash
partitions.Possible usage: range partition by date of birth then
Composite Range-Hash Partitioning
hash partition by name; store the results into the hash
partitions.
Used to range partition first, and then spreads data into list
partitions.Possible usage: range partition by date of birth then
Composite Range-List Partitioning
list partition by state, then stores the results into the list
partitions.
-Using the partitioning methods described in this section can help you tune SQL statements to
avoid unnecessary index and table scans. You can also improve the performance of massive
join operations when large amounts of data are joined together by using partition-wise joins.
Finally, partitioning data greatly improves manageability of very large databases and
dramatically reduces the time required for administrative tasks such as backup and restore.
Q2.
What is Tablespace? Show syntax for creating tablespace. Create 2
tablespace with name Cust and stud, size 5m each and save as datafile.
A database is divided into one or more logical storage units called tablespaces. A tablespace
is made up of one or more database datafiles. The total amount of storage space available in a
tablespace is the sum of the physical disk size of all the datafiles associated with that
tablespace
Syntax:SQL>Create tablespace tablespace_name
DataFile ‘D:\ tablespace_name.dat’
Size ;
SQL>.Create tablespace cust
DataFile ‘D:\cust.dat’
Size 5M;
SQL>Create tablespace stud
DataFile ‘D:\stud.dat’
Size 5M;
Q3.
Explain Range Partition. Create partition table Purchaser using range
partition on amtpaid column.
Purchaser(pur_id,pname,address,amtpaid,prod_pur).
A table that is partitioned by range is partitiones in such a way that each partition contains
rows for which the partitioning expression values lies partitioned table.It is the most common
type of partitioning and is often used with dates.
SQL>Create table Purchaser(pur_id number(10),pname varchar2(20),address
varchar2(20),amtpaid number(10),prod_pur varchar2(20))partition by
range(amtpaid)(partition p1 values less than(500) tablespace cust, partition p2 values less
than(1000) tablespace cust, partition p3 values less than(maxvalue) tablespace cust);
Q4.
Insert Five records in Purchaser table.
SQL>Insert into Purchaser Values(1,’SURAJ’,’nerul’,80,’soap’);
SQL>Insert into Purchaser Values(2,’Dinesh’,’mankhurd’,150,’maggi’);
SQL>Insert into Purchaser Values(3,’Nilam’,’kharghar’,600,’mouse’);
SQL>Insert into Purchaser Values(4,’Safa’,’vashi’,1200,’trouser’);
SQL>Insert into Purchaser Values(5,’Husna’,’pune’,900,’dress’);
Q5.
Display entire data in table and also display data partition wise.
SQL>Select * from Purchaser partition(p1);
SQL>Select * from Purchaser partition(p2);
SQL>Select * from Purchaser partition(p3);
Q6. Split any one partition into two partitions and merge any two partitions into one
partition.
SQL>Alter table Purchaser split partition p2 at(800)into (partition p21,partition p22);
SQL>alter table Purchaser
merge partitions p21,p22
into partition p2;
Q7.
Add a new partition.
SQL>Alter table Purchaser add partition p4 tablespace stud;
Q8.
Drop an existing partition.
SQL>Alter table Purchaser drop partition p4;
Q9. Explain List Partition. Create partition table scholar using List partition on city
column.
scholar(sid,sname,address,city,per_of_marks,specialization).
List partitioning enables you to explicitly control how rows map to partitions by specifying a
list of discrete values for the partitioning key in the description for each partition.
SQL>Create table scholar(sid number(5),sname varchar2(20),address varchar2(20),city
varchar2(20),per_of_marks number(10),specialization varchar2(20))partition by
list(city)(partition p2 values(‘nerul’,’vashi’,’cbd’),partition p2
values(‘virar’,’nalasopar’,’kandivali’),partition p3 values (‘up’,’mp’,’delhi’));
Q10. Insert Five records in scholar table.
SQL>Insert into scholar values(101,’rahul’,’h01’,’nerul’,80,’english’);
SQL>Insert into scholar values(102,’krish’,’a01’,’virar’,90,’maths’);
SQL>Insert into scholar values(103,’ajmat’,’n01’,’kandivali’,70,’marathi’);
SQL>Insert into scholar values(104,’aashu’,’u01’,’up’,65,’hindi’);
SQL>Insert into scholar values(105,’anuj’,’p01’,’delhi’,75,’science’);
Q11. Display entire data in table and display data partition wise.
SQL>Select * from scholar partition (p1);
SQL>Select * from scholar partition (p2);
SQL>Select * from scholar partition (p3);
Q12. Split any one partition into two partition and merge any two partition into one
partition.
SQL>Alter table scholar split partition p2 at(‘nalasopara’)into (partition p221,partition p222);
SQL>alter table scholar
merge partitions p221,p222
into partition p2;
3.
Modify an existing partition
SQL>Alter table scholar rename partition p3 to p31;
4.
Add a new partition.
SQL>Alter table scholar add partition p4 values (‘pen’,’thane’,’vapi’);
5.
Truncate an existing partition.
SQL>Alter table scholar truncate partition p4;
Q16. Explain Hash Partition. Create partition table cabinet using Hash partition
oncidcolumn.cabinet(cid,mem_name,address,state_rep,phone_number).
Hash partitioning maps data to partitions based on a hashing algorithm that oracle applies to
the partitioning key that you identify.
SQL>Create table cabinet (cid number(10),mem_name varchar2(20),address
varchar2(20),state_rep varchar2(20),phone_num number(10)) partition by hash(cid)(partition
p_hash1 tablespace t1);
Q17. Insert Five records in cabinet table.
SQL>Insert into cabinet values(101,’ram’,’thane’,’good’,8547965874);
SQL>Insert into cabinet values(105,’sham’,’vashi’,’vgood’,2658749685);
SQL>Insert into cabinet values(201,’santa’,’cbd’,’vgood’,3256987458);
SQL>Insert into cabinet values(401,’banta’,’kalwa’,’good’,9988774455;
SQL>Insert into cabinet values(407,’kapil’,’nerul’,’good’,1236547896);
Q18. Display entire data in table and display data partition wise.
SQL>Select * from cabinet;
SQL>Select * from cabinet partition(SYS_p1);
Q19. Explain Composite Partitioning.
Composite partitioning is a partitioning technique that combines some of the other
partitioning methods. The table is initially partitioned by the first data distribution method
and then each partition is sub-partitioned by the second data distribution method.
Q20. Explain RangeHashComposite Partition. Create partition table product
using Range partition on price column and Hash subpartition on pdesc
column.Product(prod_no,pdesc,price).
Composite range-hash partitioning offers the benefits of both range and hash partitioning.
With composite range-hash partitioning, Oracle first partitions by range. Then, within each
range, Oracle creates subpartitions and distributes data within them using the same hashing
algorithm it uses for hash partitioned tables.
SQL>Create tablespace t1 datafile ‘d:\t1.dat’ size 5m;
SQL>Create table product(prod_no number(10) pk,pdesc varcahr2(20),price
number(10))partition by range(price),subpartition by hash(pdesc),subpartition
template(subpartition sp1 tablespace t1, subpartition sp2 tablespace t1) (partition p1 values
less than(1000) tablespace t1, partition p2 values less than(6000) tablespace t1, partition p3
values less than(maxvalue) tablespace t1);
Q21. Insert Five records in Product table.
SQL>insert into product values(101,’mobile’,5000);
SQL>insert into product values(102,’watch’,2000);
SQL>insert into product values(113,’monitor’,7000);
SQL>insert into product values(103,’mouse’,500);
SQL>insert into product values(106,’printer’,3000);
Q22. Display entire data in table and display data partition wise and sub partition
wise.
SQL>select * from product partition(p1);
SQL>select * from product partition(p2);
SQL>select * from product partition(p3);
SQL>select * from product subpartition(sp1);
SQL>select * from product subpartition(sp2);
Q23. Explain RangeHash Partition. Create partition table Tax using Range
partition on taxamt column and List subpartition on state column.
Tax(dept_no,taxamt,state).
SQL>create table tax(deptno number primary key,taxamt number,state varchar2(20))
partition by range(taxamt) subpartition by list(state) subpartition template (subpartition east
values(‘kolkata’,’manipur’,’asam’) tablespace t1, subpartition west
values(‘maharashtra’,’gujrat’,’goa’) tablespace t2)
(partition p1 values less than (100) tablespace t1,
partition p2 values less than (200) tablespace t2,
partition p3 values less than (maxvalue) tablespace t3);
Q24. Insert Five records in Tax table.
SQL>Insert into tax values(1, 100,’maha’);
SQL>Insert into tax values (2,150,’kolkata’);
SQL>Insert into tax values(3,250,’gujrat’);
SQL>Insert into tax values(4,70,’goa’);
SQL>Insert into tax values(5,500,’asam’);
Q25. Display entire data in table and display data partition wise and subpartion wise.
SQL>select * from tax partition(p1);
SQL>select * from tax partition(p2);
SQL>select * from tax partition(p3);
SQL>select * from tax subpartition(east);
SQL>select * from tax subpartition(west);
Topic: Implementation of ETL Process
Date:
1.
2.
3.
4.
5.
Explain ETL Process
Create the Operational Tables Salest and Sales_Details
Perform Extraction
Perform Transformation
Perform Loading the data into the Warehouse
DISPLAY DATA OF SALEST:
S_PERSON ITEM_SOLD PRICE
NUM_ITEM_SOLD
S_DT
ITEM_CATEG
—————- —————- ————- ————- —————- ———————–
Mayuri
2
12000
01-FEB-12
hardware
Chandrika
1
1500
02-FEB-12
software
Pallavi
1
Shraddha
2
10000
01-FEB-12
hardware
4
Shweta
2
8000
01-FEB-12
software
7
Siya
Sharvari
3
1
15000
6000
02-FEB-12
01-FEB-12
2500 01-FEB-12
5
3
hardware
software
software
10
5
Nikki
3
5000
02-FEB-12
hardware
13
Rucha
2
7000
2-FEB-12
hardware
2
Neha
3
7500
02-FEB-12
hardware
4
10 rows selected.
DISPLAY DATA OF SALES_DETAILS:
SALES_PERSON ITEM_NAME ITEM_PRICE S ALES_DAT
NO_OF_ITEM_SOLD
BRANCH
3
——————— —————— ————— —————- ————- ————–
Mayuri
HardDisk
12000
01-FEB-12
Chandrika
AntiVirus
1500
Pallavi
CPU
1500
Shraddha
RAM
10000
01-FEB-12
Andheri
5
Sharvari
HardDisk
12000
11-FEB-12
Thane
4
Rucha
AntiVirus
1500
11-MAR-12 CST
02-FEB-12
02-FEB-12
Thane
2
CST
3
Thane
2
2
6 rows selected.
EXTRACTION
DISPLAY DATA OF SALES_RECORDS AFTER ADDING DATA FORM SALEST:
SUPPLIER
ITEM_NAME PRICE
NUM_ITEM_SOLD
SALES_DT BRANCH ITEM_CATEG
————— —————– ———- ———— ———— —————– ————Mayuri
hardware
12000
01-FEB-12
Chandrika
software
1500
02-FEB-12
Pallavi
hardware
15000
Shraddha
hardware
10000
Shweta
software
8000
Siya
Sharvari
software
software
software
02-FEB-12
01-FEB-12
01-FEB-12
6000 01-FEB-12
2500
hardware
01-FEB-12
5
3
hardware
hardware
4
software
software
3
7
10
software
5
Nikki
13
hardware
5000
02-FEB-12
hardware
Rucha
hardware
7000
02-FEB-12
hardware
2
Neha
hardware
7500
02-FEB-12
hardware
4
10 rows selected.
DISPLAY DATA OF SALES_RECORDS AFTER ADDING DATA FORM
SALES_DETAILS:
SUPPLIER
ITEM_NAME PRICE
NUM_ITEM_SOLD
SALES_DT BRANCH
ITEM_CATEG
————— —————– ———– ———— ———— —————— ————Mayuri
hardware
12000
01-FEB-12
Chandrika
software
1500
02-FEB-12
Pallavi
hardware
15000
hardware
software
02-FEB-12
5
3
hardware
3
Shraddha
hardware
10000
01-FEB-12
hardware
4
Shweta
software
8000
01-FEB-12
software
7
Siya
10
Sharvari
software
software
6000
2500
01-FEB-12
software
01-FEB-12
software
5
Nikki
13
hardware
5000
02-FEB-12
hardware
Rucha
hardware
7000
02-FEB-12
hardware
2
Neha
hardware
7500
02-FEB-12
hardware
4
Mayuri
HardDisk
12000
01-FEB-12
Thane
Chandrika
3
AntiVirus
1500
02-FEB-12
CST
2
Pallavi
2
Shraddha
CPU
1500
02-FEB-12
Thane
RAM
10000
01-FEB-12
Andheri
5
Thane
4
Sharvari
HardDisk
12000
11-FEB-12
Rucha
AntiVirus
1500
11-MAR-12 CST
2
16 rows selected.
TRANSFORMATION
DISPLAY DATA OF SALES_DETAILS:
SALES_PERSON ITEM_NAME
NO_OF_ITEM_SOLD
ITEM_PRICE
SALES_DAT
BRANCH
——————— ——————– —————– ————— —————– —————
——–
Mayuri
Thane
HardDisk
Chandrika
AntiVirus
Pallavi
Thane
2
Shraddha
Andheri
5
Sharvari
Thane
4
CPU
RAM
Rucha
CST
Gargi
mumbai
12000
01-FEB-12
2
1500
02-FEB-12
1500
10000
CST
02-FEB-12
01-FEB-12
HardDisk
12000
11-FEB-12
AntiVirus
1500
11-MAR-12
HardDisk
5000
03-JAN-12
2
2
3
7 rows selected.
DISPLAY DATA OF SALES_RECORDS AFTER UPDATING BRANCH FIELD:
SUPPLIER
ITEM_NAME PRICE
ITEM_CATEG NUM_ITEM_SOLD
—————– —————–
———-
SALES_DT BRANCH
———- ————- ————– —————-
Mayuri
5
hardware
Chandrika
3
software
Pallavi
hardware
hardware
3
Shraddha
4
hardware
10000
01-FEB-12
unknown
hardware
Shweta
7
software
8000
01-FEB-12
unknown
software
Siya
10
Sharvari
5
software
software
Nikki
13
hardware
Rucha
2
hardware
Neha
4
Mayuri
12000
1500
15000
6000
2500
5000
01-FEB-12
02-FEB-12
02-FEB-12
01-FEB-12
01-FEB-12
unknown
————
unknown
hardware
software
unknown
unknown
unknown
software
software
02-FEB-12
unknown
hardware
7000
02-FEB-12
unknown
hardware
hardware
7500
02-FEB-12
unknown
hardware
HardDisk
2
12000
01-FEB-12
Thane
Chandrika
CST
Pallavi
Thane
Shraddha
Andheri
AntiVirus
1500
3
02-FEB-12
CPU
1500
2
RAM
10000
5
01-FEB-12
11-FEB-12
Sharvari
Thane
HardDisk
12000
4
Rucha
AntiVirus
2
1500
02-FEB-12
11-MAR-12
CST
16 rows selected.
DISPLAY DATA OF SALES_RECORDS AFTER UPDATING CATEGORY FIELD:
SUPPLIER
ITEM_NAME
PRICE
ITEM_CATEG NUM_ITEM_SOLD
SALES_DT BRANCH
—————– ——————– ———— ————– ————— ————— ———
————
Mayuri
hardware
12000
01-FEB-12
unknown
hardware
5
Chandrika
software
1500
02-FEB-12
unknown
software
3
15000
02-FEB-12
hardware
3
Pallavi
hardware
Shraddha
hardware
10000
Shweta
software
8000
Siya
10
Sharvari
software
software
Nikki
13
hardware
Rucha
hardware
6000
2500
5000
7000
01-FEB-12
01-FEB-12
01-FEB-12
01-FEB-12
unknown
unknown
unknown
unknown
unknown
hardware
software
4
7
software
software
02-FEB-12
unknown
hardware
02-FEB-12
unknown
hardware
5
2
Neha
hardware
Mayuri
2
HardDisk
12000
01-FEB-12
Thane
Chandrika
software
AntiVirus
3
1500
02-FEB-12
CST
Pallavi
2
Shraddha
5
7500
02-FEB-12
02-FEB-12
unknown
hardware
4
hardware
CPU
1500
Thane
RAM
10000
01-FEB-12
Andheri
hardware
hardware
Sharvari
4
HardDisk
12000
11-FEB-12
Thane
Rucha
software
AntiVirus
2
1500
11-MAR-12
CST
hardware
16 rows selected.
DISPLAY DATA OF SALES_RECORDS AFTER UPDATING NUM ITEM SOLD
FIELD:
SUPPLIER
ITEM_NAME
NUM_ITEM_SOLD
PRICE SALES_DT BRANCH
ITEM_CATEG
————— ——————– ———- ———— ————– —————— ——————
——
Mayuri
hardware
12000 01-FEB-12 unknown hardware
5
Chandrika
software
1500
02-FEB-12 unknown software
3
15000
02-FEB-12 unknown hardware
3
Pallavi
hardware
Shraddha
hardware
10000
01-FEB-12 unknown
hardware
Shweta
software
8000
01-FEB-12 unknown
software
Siya
Sharvari
software
software
6000
2500
01-FEB-12 unknown
01-FEB-12
software
unknown software
4
7
10
5
Nikki
hardware
5000
02-FEB-12 unknown
hardware
13
Rucha
hardware
7000
02-FEB-12 unknown
hardware
2
Neha
hardware
7500
02-FEB-12
hardware
4
Mayuri
HardDisk
12000
01-FEB-12
Thane
hardware
Chandrika
AntiVirus
1500
02-FEB-12
CST
software
5
Pallavi
CPU
1500
Thane
hardware
2
Shraddha
RAM
10000
Sharvari
HardDisk
12000 11-FEB-12
Rucha
AntiVirus
1500
unknown
02-FEB-12
01-FEB-12
2
Andheri
hardware
5
Thane
hardware
4
11-MAR-12 CST
software
5
16 rows selected.
SUPPLIER
ITEM_NAME PRICE SALES_DT BRANCH ITEM_CATEG
NUM_ITEM_SOLD
————— ——————– ——– ————– ————- —————– ———————
—
Mayuri
hardware
12000 01-FEB-12
unknown hardware
5
Chandrika
software
1500
unknown software
3
Pallavi
hardware
15000 02-FEB-12
unknown hardware
3
Shraddha
hardware
10000 01-FEB-12
Shweta
software
8000
Siya
Sharvari
software
software
02-FEB-12
01-FEB-12
unknown hardware
unknown software
unknown software
4
7
6000
01-FEB-12
10
2500
01-FEB-12 unknown software
5
Nikki
hardware
5000
02-FEB-12 unknown hardware
13
Rucha
hardware
7000
02-FEB-12 unknown hardware
2
Neha
hardware
7500
02-FEB-12
4
unknown hardware
Mayuri
HardDisk
12000 01-FEB-12 Thane
Chandrika
AntiVirus
1500
Pallavi
CPU
Shraddha
RAM
10000 01-FEB-12
Andheri
Sharvari
HardDisk
12000 11-FEB-12
Thane
Rucha
AntiVirus
1500
1500
CST
software
5
02-FEB-12
Thane
hardware
5
11-MAR-12 CST
LOADING
DISPLAY DATA OF VIEW CATALOG1:
SALE YEAR
———–
519500
—2012
DISPLAY DATA OF VIEW CATALOG2:
YEARLY_
———–
519500 12
SALE YE
—
5
02-FEB-12
16 rows selected.
YEARLY_
hardware
hardware
hardware
software
5
5
5
DISPLAY DATA OF VIEW CATEGORY:
SUPPLIER
ITEM_NAME
NUM_ITEM_SOLD
PRICE
SALES_DT BRANCH ITEM_CATEG
————— ——————– ———- ————– ———— ——————- ————Chandrika
software
1500
02-FEB-12 unknown software
3
Shweta
software
8000
01-FEB-12 unknown software
7
Siya
Sharvari
software
software
6000
2500
01-FEB-12 unknown software
01-FEB-12 unknown software
10
5
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Assignment 3
METHODS:-
Create an abstract datatypebook_ty with fields
bname,
price,
pub_date,
member function getbookprice which calculates the discount passed by the user to the
function
member function findyearsold which calculates the no of years since book was published
Create a book table (bookid, book_details)where book_details is of book_ty
a). Dsiplay all records from the table
b). Display all the records where the price is lower than 1000
c). Find out the books which are having the minimum price after the given discount
d). Find the most recently published book
1)
BOOK_ID BOOK_DETAILS.BNAME BOOK_DETAILS.PRICE BOOK_DETAILS.PUB_DATE
1
PHP
420
01-JAN-00
2
JAVA
1520
23-MAR-89
3
.net
1600
15-APR-90
4
HTML
2400
12-DEC-92
2)
BOOK_ID BOOK_DETAILS.BNAME BOOK_DETAILS.PRICE BOOK_DETAILS.PUB_DATE
1
PHP
3)
MIN(DISCOUNTED)
419
4)
BNAME MIN(RECENT_BOOK)
420
01-JAN-00
PHP
14
INHERITANCE:-
Create the following type:
Shapes_TY
Shape_ID
Length
Square_TY
Member function area_s to calculate the area of the square
Rectangle_TY
breadth
Member function area_r to calculate the area of the rectangle
Triangle_TY
base
Member function area_t to calculate the area of the triangle
Create a table shapes of type Shapes_TY
a). Display all length of rectangle which is between 3 and 7
b). Display all information of the reactangle where the area is greater than 70
c). Display all information of Square, Rectangle and Triangle
1)
LENGTH
4
5
2)
AREA
4000
120
3)
square
LENGTH AREA
10
100
5
25
6
36
7
49
Rectangle
LENGTH BREADTH AREA
40
100
4000
10
12
120
4
10
40
5
12
60
Triangle
LENGTH BASE AREA
10
12
60
9
11
50
8
10
40
7
9
32
6
8
24
REFERENCE:Create the following type:
Dept_ty
Dname
Dno
Location
Create the table department of dept_ty
Create the table employee (eid, ename,hdate, dept) where dept should refer to the object
table created above.
a). Display all the employee working in the department 20 and 30
b). Display all employees working in the location that begins with ‘N’
c). Display department wise count of employees hired after the month of april 2009
1)
EID ENAME DEREF(DEPT).NAME
15 Baker
IT
14 Jems
Admin
13 Bob
IT
2)
EID ENAME DEREF(DEPT).NAME
10 scott
MGR
11 Bill
MGR
3)
DEREF(DEPT).DNO COUNT(*)
20
1
10
1
TYPE INHERITANCE AND OVERRIDING:-
Create super type:
Person_TY
Name
Address
Age
Member function Tostring which shall return values based upon the age as follows:
Age<13
Child
Age between 13 and 19
Teens
Age between 20 and 55
Middle aged
Else
Old
Create sub type
Student_TY
Course
Balance
Member procedure payment which shall take an amount and deduct the amount from the
balance
Member function ToString which shall display the values in the following format:
Name:age:course:balance
a). Write an anonymous code block to display the value of the member functions
Output:a)Middle agedStatement processed.
a)
Allen:22:TEST:5000Allen:22:TEST:4800 Statement processed.
++++++++++++++++++++++++++++++++++++++++++++++
Topic: OLAP (On Line Analytical Processing)
Date:
OLAP ANALYTICAL FUNCTIONS
They are also known as windowing functions.
Analytic function also operates on subsets of rows, similar to aggregate functions in group by
queries, but they do not reduce the number of rows returned by the query.
ROLLUP:
Rollup summarizes data by climbing up hierarchy or by dimension reduction
Creating Table:
SQL> CREATE TABLE Sales
(
year varchar(4),
region varchar(20),
dept varchar(4),
profit number
);
Table created.
Inserting Data into table
SQL> INSERT INTO Sales VALUES(1999,’North’,’IT’10);
SQL> INSERT INTO Sales VALUES(2000,’South’,’Prod’,25);
SQL> INSERT INTO Sales VALUES(2001,’West’,’Sale’,30)
SQL> INSERT INTO Sales VALUES(2002,’East’,’PR’,40);
SQL> INSERT INTO Sales VALUES(2003,’North’,’IT’,35);
SQL> INSERT INTO Sales VALUES(2004,’South’,’Prod’,20);
SQL> INSERT INTO Sales VALUES(1999,’South’,’IT’,23);
SQL> INSERT INTO Sales VALUES(2000,’West’,’IT’,4);
Displaying Data from table:
SQL> SELECT * FROM sales;
YEAR REGION DEPT PROFIT
—- ——- —- ——
2000 South Prod
2003 North IT
2004 South Prod
25
35
20
1999 South IT
23
2000 West
4
IT
SQL> SELECT year,region,dept,sum(profit)
FROM Sales GROUP BY ROLLUP(year,region,dept);
YEAR REGION
DEPT SUM(PROFIT)
—- ——————– —- ———–
1999 South
IT
23
1999 South
23
1999
2000 West
23
IT
4
2000 West
2000 South
4
Prod
25
2000 South
25
2000
2003 North
2003 North
29
IT
35
35
2003
35
2004 South
Prod
20
2004 South
20
2004
20
107
15 rows selected.
SQL> SELECT year,dept,sum(profit)
FROM Sales GROUP BY ROLLUP(year,dept);
YEAR DEPT SUM(PROFIT)
—- —- ———–
1999 IT
1999
23
23
2000 IT
4
2000 Prod
25
2000
2003 IT
2003
2004 Prod
2004
29
35
35
20
20
107 10 rows selected.
SQL> SELECT region,dept,sum(profit)
FROM Sales group by rollup(region,dept);
REGION
DEPT SUM(PROFIT)
——————– —- ———–
West
IT
4
West
4
North
IT
35
North
35
South
IT
23
South
Prod
South
45
68
107
8 rows selected.
PARTIAL ROLLUP:
SQL> SELECT region,dept,sum(profit)
FROM Sales GROUP BY year,ROLLUP(region,dept);
REGION DEPT SUM(PROFIT)
——- —- ———–
South IT
South
23
23
23
West
IT
West
South Prod
4
4
25
South
25
29
North IT
35
North
35
35
REGION DEPT SUM(PROFIT)
——- —- ———–
South Prod
20
South
20
20
14 rows selected.
SQL> SELECT year,region,dept,sum(profit)
FROM Sales GROUP BY year,ROLLUP(region,dept);
YEAR REGION DEPT SUM(PROFIT)
—- ——- —- ———–
1999 South IT
23
1999 South
23
1999
2000 West
23
IT
2000 West
2000 South Prod
4
4
25
2000 South
25
2000
29
2003 North IT
35
2003 North
35
2003
35
YEAR REGION DEPT SUM(PROFIT)
—- ——- —- ———–
2004 South Prod
20
2004 South
20
2004
20
14 rows selected.
CUBE:
SQL> SELECT year,region,dept,sum(profit)
FROM Sales GROUP BY cube(year,region,dept);
YEAR REGION DEPT SUM(PROFIT)
—- ——- —- ———–
107
IT
Prod
West
62
45
4
West
IT
4
North
35
North IT
35
South
68
South IT
23
South Prod
45
1999
23
1999
IT
23
1999 South
23
1999 South IT
2000
23
29
2000
IT
4
2000
Prod
25
2000 West
2000 West
4
IT
4
2000 South
25
2000 South Prod
2003
2003
25
35
IT
35
2003 North
35
2003 North IT
2004
2004
35
20
Prod
2004 South
2004 South Prod
20
20
20
29 rows selected.
PARTIAL CUBE:
SQL> select region,dept,sum(profit)
from Sales group by year,cube(region,dept);
REGION DEPT SUM(PROFIT)
——- —- ———–
23
IT
23
South
23
South IT
23
29
IT
4
Prod
25
West
West
4
IT
South
4
25
South Prod
25
35
IT
35
North
North IT
20
35
35
Prod
20
South
South Prod
20
20
19 rows selected.
RANK:
Rank calculates the rank of value in group of values. The return type is number.
SQL>CREATE TABLE Emp1
(
Emp_id varchar(20) primary key,
Emp_name varchar(20),
Dept_no varchar(20),
Sal number
);
Table created.
Inserting Data into Table
SQL>INSERT INTO Emp1 VALUES(‘E101′,’ Varsha’,’ D1′, 20000);
SQL>INSERT INTO Emp1 VALUES(‘E102′,’ Ashish’,’ D2′,25000);
SQL>INSERT INTO Emp1 VALUES(‘E103′,’ Ritu’,’ D1′, 20000);
SQL>INSERT INTO Emp1 VALUES(‘E104′,’Jhon’,’D1′, 5000);
SQL>INSERT INTO Emp1 VALUES(‘E105′,’Robert’,’ D2′,10000);
SQL>INSERT INTO Emp1 VALUES(‘E106′,’ Rock’,’ D2′, 25000);
SQL>INSERT INTO Emp1 VALUES(‘E107′,’ Maddy’,’ D3′, 12000);
SQL>INSERT INTO Emp1 VALUES(‘E108′,’Tom’,’ D3′, 20000);
SQL>INSERT INTO Emp1 VALUES(‘E109′ ,’leena’,’ D1′,25000);
Displaying Data from table:
SQL> SELECT * FROM Emp1;
EMP_ID EMP_NAME DEPT_NO
SAL
—————- —————
E101 Varsha
D1
20000
E102 Ashish
D2
25000
E103 Ritu
D1
20000
E104 Jhon
D1
5000
E105 Robert
D2
10000
E106 Rock
D2
25000
E107 Maddy
D3
12000
E108 Tom
D3
20000
E109 leena
D1
25000
Ascending Order>>
SQL> SELECT Emp_id,Dept_no,Sal,
RANK()OVER(PARTITION BY Dept_no ORDER BY Sal)
FROM Emp1;
EMP_ID DEPT_NO
SAL RANK()
——————— ——–
E101 D1
20000
1
E103 D1
20000
1
E109 D1
25000
3
E105 D2
10000
1
E102 D2
25000
2
E106 D2
25000
2
E107 D3
12000
1
E108 D3
20000
2
E104 D1
5000
1
9 rows selected.
Descending>>
SQL> SELECT Emp_id,Dept_no,Sal,
RANK()OVER(PARTITION BY Dept_no ORDER BY Sal DESC) FROM Emp1;
EMP_ID DEPT_NO SAL RANK()
—— ——
— —-
E109
D1
25000 1
E101
D1
20000 2
E103
D1
20000 2
E102
D2
25000 1
E106
D2
25000 1
E105
D2
10000 3
E108
D3
20000 1
E107
D3
12000 2
E104
D1
5000 1
9 rows selected.
DENSE_RANK():
It computes the rank of row in ordered group of rows and return the rank as number
SQL> SELECT Emp_id,Dept_no,Sal,
DENSE_RANK()OVER(PARTITION BY Dept_no ORDER BY Sal)
FROM Emp1;
EMP_ID DEPT_NO
SAL DENSE_RANK()
—— ——- —– —E101
D1
20000 1
E103
D1
20000 1
E109
D1
25000 2
E105
D2
10000 1
E102
D2
25000 2
E106
D2
25000 2
E107
D3
12000 1
E108
D3
20000 2
E104
D1
5000 1
9 rows selected.
SQL> SELECT Emp_id,Dept_no,Sal,
Dense_rank()over(partition by Dept_no order by Sal desc)
FROM Emp1;
EMP_ID DEPT_NO
SAL DENSE_RANK()
———————————–
E109
D1
25000 1
E101
D1
20000 2
E103
D1
20000 2
E102
D2
25000 1
E106
D2
25000 1
E105
D2
10000 2
E108
D3
20000 1
E107
D3
12000 2
E104
D1
5000 1
9 rows selected.
FIRST AND LAST:
These functions are used to returned first and last value from ordered sequence.
SQL> SELECT emp_id,dept_no,Sal,
min(Sal) keep(Dense_rank FIRST ORDER BY Sal) over(PARTITION BY Dept_no)
“Lowest” FROM Emp1;
EMP_ID DEPT_NO
SAL
——- ————– ———E101
D1
20000
20000
Lowest
E103
D1
20000
20000
E109
D1
25000
20000
E102
D2
25000
10000
E106
D2
25000
10000
E105
D2
10000
10000
E107
D3
12000
12000
E108
D3
20000
12000
E104
D1
5000
5000
9 rows selected.
SQL> SELECT emp_id,dept_no,Sal,
max(Sal) keep(Dense_rank LAST ORDER BY Sal) over(PARTITION BY Dept_no)
“Highest” FROM Emp1;
EMP_ID DEPT_NO
SAL Highest
——- —————- ———E101
D1
20000
25000
E103
D1
20000
25000
E109
D1
25000
25000
E102
D2
25000
25000
E106
D2
25000
25000
E105
D2
10000
25000
E107
D3
12000
20000
E108
D3
20000
20000
E104
D1
5000
5000
9 rows selected.
LEAD:
-It provides access to more than one row at the same time without self join.
-Give the series of rows returned from query and position of cursor, LEAD provides access to
row at a given physical offset beyond that position.
If you do not specify the offset the default is one.
Displaying Data from table
SQL> SELECT * FROM Emp1;
EMP_ID EMP_NAME DEPT_NO
——- ——— —————E101
Varsha
D1
20000
E102
Ashish
D2
25000
E103
Ritu
D1
20000
E104 Jhon
D1
5000
E105 Robert
D2
10000
E106
Rock
D2
25000
E107
Maddy
D3
12000
E108 Tom
D3
20000
E109 leena
D1
25000
9 rows selected.
SAL
Display the joining date of all employee joined JUST AFTER joining date of each
employee in the employee table.
SQL> select ename,job,hiredate,lead(hiredate,1)
over(order by hiredate desc) as “Next Joined” from emp;
ENAME
JOB
HIREDATE NEXT_JOINED
———- ——— ——— ———
ADAMS
CLERK
23-MAY-87 19-APR-87
SCOTT
ANALYST 19-APR-87 23-JAN-82
MILLER
CLERK
23-JAN-82 03-DEC-81
JAMES
CLERK
03-DEC-81 03-DEC-81
FORD
ANALYST 03-DEC-81 17-NOV-81
KING
PRESIDENT 17-NOV-81 28-SEP-81
MARTIN
SALESMAN 28-SEP-81 08-SEP-81
TURNER
SALESMAN 08-SEP-81 09-JUN-81
CLARK
MANAGER 09-JUN-81 01-MAY-81
BLAKE
MANAGER 01-MAY-81 02-APR-81
JONES
MANAGER 02-APR-81 22-FEB-81
WARD
SALESMAN 22-FEB-81 20-FEB-81
ALLEN
SALESMAN 20-FEB-81 17-DEC-80
SMITH
CLERK
17-DEC-80
14 rows selected.
LAG :
-It provides access to more than one row at the same time without selfjoin.
-Give the series of rows returned from query and position of cursor,LEAD provides access to
row at a given physical offset prior that position.
If you do not specify the offset the default is one.
Display the joining date of all employee joined JUST BEFORE joining date of each
employee in the employee table.
SQL> select ename,job,hiredate,lag(hiredate,1)
over(order by hiredate desc) as Before from emp;
ENAME
JOB
HIREDATE BEFORE
———- ——— ——— ———
ADAMS
CLERK
23-MAY-87
SCOTT
ANALYST 19-APR-87 23-MAY-87
MILLER
CLERK
23-JAN-82 19-APR-87
JAMES
CLERK
03-DEC-81 23-JAN-82
FORD
ANALYST 03-DEC-81 03-DEC-81
KING
PRESIDENT 17-NOV-81 03-DEC-81
MARTIN
SALESMAN 28-SEP-81 17-NOV-81
TURNER
SALESMAN 08-SEP-81 28-SEP-81
CLARK
MANAGER 09-JUN-81 08-SEP-81
BLAKE
MANAGER 01-MAY-81 09-JUN-81
JONES
MANAGER 02-APR-81 01-MAY-81
WARD
SALESMAN 22-FEB-81 02-APR-81
ALLEN
SALESMAN 20-FEB-81 22-FEB-81
SMITH
CLERK
17-DEC-80 20-FEB-81
14 rows selected.
ROW_NUMBER():
-RowNumber appears to be a function for assigning row numbers to a result returned by a
query or subquery or partition.
Assign row numbers in descending order of salary. Display the table in ascending order
of commission where null values of commission should come last
SQL> select row_number() over(order by sal desc) as rank, empno, ename, sal, comm from
emp order by comm NULLs LAST ;
RANK
EMPNO ENAME
SAL
—– ———- ————- ———8
7844 TURNER 1500
7
7499 ALLEN 1600
10
7521 WARD
11
7654 MARTIN 1250
1
7839 KING
2
7788 SCOTT
1250
5000
3000
12
7876 ADAMS
1100
14
7369 SMITH
800
13
7900 JAMES
950
3
7902 FORD
3000
9
7934 MILLER 1300
4
7566 JONES
2975
0
300
500
1400
COMM
5
7698 BLAKE 2850
6
7782 CLARK 2450
PERCENT_RANK():
- The range of values returned by PERCENT_RANK is 0 to 1, inclusive. The first row in any
set has a PERCENT_RANK of 0. The return value is NUMBER.
Display empno,ename,sal and percent rank of employee
SQL> select (percent_rank() over(order by sal)*100)
as “PERCENT RANK” ,empno, ename, sal from emp;
PERCENT RANK EMPNO ENAME
———- ———- ————–
0
7369 SMITH
800
7.69230769
7900 JAMES
950
15.3846154
7876 ADAMS
1100
23.0769231
7521 WARD
23.0769231
7654 MARTIN
1250
38.4615385
7934 MILLER
1300
46.1538462
7844 TURNER
1500
53.8461538
7499 ALLEN
1600
61.5384615
7782 CLARK
2450
69.2307692
7698 BLAKE
2850
76.9230769
7566 JONES
2975
84.6153846
7788 SCOTT
3000
1250
SAL
84.6153846
100
7902 FORD
7839 KING
3000
5000
14 rows selected.
Display empno,ename,sal and percent rank of employee for department number 30
SQL> select (percent_rank() over(order by sal)*100)
as “PERCENT RANK”,empno,ename,sal,deptno
from emp where deptno=30;
PERCENT RANK
EMPNO ENAME
SAL
DEPTNO
———— ———- ———— ———0
7900 JAMES
950
20
7521 WARD
20
7654 MARTIN 1250
30
60
7844 TURNER 1500
30
80
7499 ALLEN 1600
100
1250
30
7698 BLAKE 2850
30
30
30
6 rows selected.
NTILE():
-NTILE is an analytic function. It divides an ordered data set into a number of buckets
indicated by expr and assigns the appropriate bucket number to each row. The buckets are
numbered 1 through expr. The expr value must resolve to a positive constant for each
partition. Oracle Database expects an integer, and if expr is a noninteger constant, then
Oracle truncates the value to an integer. The return value is NUMBER.
Display employee details according to quartile on sal
SQL> select ntile(4) over(order by sal) as quertile, ename, sal
from emp;
QUERTILE ENAME
———- ———- ———1 SMITH
800
1 JAMES
950
1 ADAMS
1100
1 WARD
1250
2 MARTIN
1250
2 MILLER
1300
2 TURNER
1500
2 ALLEN
1600
3 CLARK
2450
3 BLAKE
2850
3 JONES
2975
4 SCOTT
3000
4 FORD
3000
4 KING
5000
14 rows selected.
WINDOWING CLAUSE:
SAL
The group of rows is called a window and is defined by the analytic_clause. For each row, a
sliding window of rows is defined. The window determines the range of rows used to perform
the calculations for the current row.
Display empno,name,deptno,sal and sum of sal department wise and display the sal of
current and previous two records
SQL> select empno,ename,deptno,sal,sum(sal)
over(partition by deptno order by sal rows 2 preceding) as total
from emp;
EMPNO ENAME
DEPTNO
SAL
———- ———- ———- ———- ———7934 MILLER
10
1300
1300
7782 CLARK
10
2450
3750
7839 KING
7369 SMITH
7876 ADAMS
10
20
20
5000
8750
800
800
1100
1900
7566 JONES
20
2975
4875
7788 SCOTT
20
3000
7075
7902 FORD
20
3000
8975
7900 JAMES
30
950
950
7521 WARD
30
1250
2200
7654 MARTIN
30
1250
3450
7844 TURNER
30
1500
4000
7499 ALLEN
30
1600
4350
7698 BLAKE
30
2850
5950
TOTAL
14 rows selected.
Display empno,name,deptno and sum of salary for three earlier row and one next row
department wise
SQL> select empno,ename,deptno,sal,sum(sal) over(partition by
deptno order by sal rows between 3 preceding and
1 following)as total from emp;
EMPNO ENAME
DEPTNO
SAL
———- ———- ———- ———- ———7934 MILLER
10
1300
3750
7782 CLARK
10
2450
8750
7839 KING
7369 SMITH
7876 ADAMS
10
20
20
5000
8750
800
1900
1100
4875
7566 JONES
20
2975
7875
7788 SCOTT
20
3000
10875
7902 FORD
20
3000
10075
7900 JAMES
30
950
2200
7521 WARD
30
1250
3450
7654 MARTIN
30
1250
4950
7844 TURNER
30
1500
6550
7499 ALLEN
30
1600
8450
TOTAL
7698 BLAKE
30
2850
7200
14 rows selected.
Display empno, name, deptno, sum of salary for all preceding row and current row
department wise
SQL> select empno,ename,deptno,sal,sum(sal) over (partition by deptno order by sal rows
between unbounded preceding and current row) as total from emp;
EMPNO ENAME
DEPTNO
SAL
———- ———- ———- ———- ———7934 MILLER
10
1300
1300
7782 CLARK
10
2450
3750
7839 KING
7369 SMITH
7876 ADAMS
10
20
20
5000
8750
800
800
1100
1900
7566 JONES
20
2975
4875
7788 SCOTT
20
3000
7875
7902 FORD
20
3000
10875
7900 JAMES
30
950
950
7521 WARD
30
1250
2200
7654 MARTIN
30
1250
3450
7844 TURNER
30
1500
4950
7499 ALLEN
30
1600
6550
7698 BLAKE
30
2850
9400
TOTAL
14 rows selected.
Display empno, name, department, sal, sum of salary for 3 preceding row and 1
preceding row department wise
SQL> select empno,ename,deptno,sal,sum(sal) over (partition by deptno order by sal rows
between 3 preceding and 1 preceding) as total from emp;
EMPNO ENAME
DEPTNO
SAL
———- ———- ———- ———- ———7934 MILLER
10
1300
7782 CLARK
10
2450
7839 KING
7369 SMITH
7876 ADAMS
10
5000
20
20
1300
3750
800
1100
800
7566 JONES
20
2975
1900
7788 SCOTT
20
3000
4875
7902 FORD
20
3000
7075
7900 JAMES
30
950
7521 WARD
30
1250
950
7654 MARTIN
30
1250
2200
7844 TURNER
30
1500
3450
7499 ALLEN
30
1600
4000
7698 BLAKE
30
2850
4350
TOTAL
14 rows selected.
Display empno, name, deptno, sal, sum of salary for 1 following and 3 following row
department wise
SQL> select empno,ename,deptno,sal,sum(sal) over (partition by deptno order by sal rows
between 1 following and 3 following) as total from emp;
EMPNO ENAME
DEPTNO
SAL
———- ———- ———- ———- ———7934 MILLER
10
1300
7450
7782 CLARK
10
2450
5000
7839 KING
7369 SMITH
7876 ADAMS
10
5000
20
20
800
1100
7075
8975
7566 JONES
20
2975
6000
7788 SCOTT
20
3000
3000
7902 FORD
20
3000
7900 JAMES
30
950
7521 WARD
30
1250
4000
4350
7654 MARTIN
30
1250
5950
7844 TURNER
30
1500
4450
7499 ALLEN
30
1600
7698 BLAKE
30
2850
2850
TOTAL
14 rows selected.
CASE EXPRESSION:
Write a query for finding the average of salary where if salary is less than 2000 then
consider it as 2000
SQL> select avg(case when sal > 2000 then sal else 2000 end ) as “average of salary” from
emp;
average of salary
—————–
2519.64286
Write a query to find out the average of salary where the salary is greater than 2000
SQL> select avg(case when sal > 2000 then sal else NULL end )as “average of salary” from
emp;
average of salary
—————–
3212.5
Display empno, name, salary and caption for salary such that
When sal< 1000 then low
When sal is between1000 and 3000 then Medium
When sal> 3000 then High
Else Not Applicable
SQL> select empno,ename, sal ,
case when sal < 1000 then ‘Low’
when sal between 1000 and 3000 then ‘Medium’
when sal >3000 then ‘High’
else ‘Not Applicable’ end as caption
from emp;
EMPNO ENAME
SAL CAPTION
———- ———- ———- ————–
7369 SMITH
800 Low
7499 ALLEN
1600 Medium
7521 WARD
1250 Medium
7566 JONES
2975 Medium
7654 MARTIN
1250 Medium
7698 BLAKE
2850 Medium
7782 CLARK
2450 Medium
7788 SCOTT
3000 Medium
7839 KING
5000 High
7844 TURNER
1500 Medium
7876 ADAMS
1100 Medium
7900 JAMES
950 Low
7902 FORD
7934 MILLER
3000 Medium
1300 Medium
14 rows selected.
++++++++++++++++++++++++++++++++++++++++++++
Topic: Data Mining
Date:
Data Mining Algorithms
ARFF file for Data Mining (contact_lenses.arff):
@relation contact-lenses
@attribute age
{young,pre-presbyopic,presbyopic}
@attribute spectacle-prescrip{myope,hypermetrope}
@attribute astigmatism
{no,yes}
@attribute tear-prod-rate
{reduced,normal}
@attribute contact-lenses
{soft,hard,none}
@data
24 instances
young,myope,no,reduced,none
young,myope,no,normal,soft
young,myope,yes,reduced,none
young,myope,yes,normal,hard
young,hypermetrope,no,reduced,none
young,hypermetrope,no,normal,soft
young,hypermetrope,yes,reduced,none
young,hypermetrope,yes,normal,hard
pre-presbyopic,myope,no,reduced,none
pre-presbyopic,myope,no,normal,soft
pre-presbyopic,myope,yes,reduced,none
pre-presbyopic,myope,yes,normal,hard
pre-presbyopic,hypermetrope,no,reduced,none
pre-presbyopic,hypermetrope,no,normal,soft
pre-presbyopic,hypermetrope,yes,reduced,none
pre-presbyopic,hypermetrope,yes,normal,none
presbyopic,myope,no,reduced,none
presbyopic,myope,no,normal,none
presbyopic,myope,yes,reduced,none
presbyopic,myope,yes,normal,hard
presbyopic,hypermetrope,no,reduced,none
presbyopic,hypermetrope,no,normal,soft
presbyopic,hypermetrope,yes,reduced,none
presbyopic,hypermetrope,yes,normal,none
ARFF file for Data Mining (weather.arff):
@relation weather
@attribute outlook {sunny, overcast, rainy}
@attribute temperature real
@attribute humidity real
@attribute windy {TRUE, FALSE}
@attribute play {yes, no}
@data
sunny,85,85,FALSE,no
sunny,80,90,TRUE,no
overcast,83,86,FALSE,yes
rainy,70,96,FALSE,yes
rainy,68,80,FALSE,yes
rainy,65,70,TRUE,no
overcast,64,65,TRUE,yes
sunny,72,95,FALSE,no
sunny,69,70,FALSE,yes
rainy,75,80,FALSE,yes
sunny,75,70,TRUE,yes
overcast,72,90,TRUE,yes
overcast,81,75,FALSE,yes
rainy,71,91,TRUE,no
PREPROCESSING:
Data pre-processing is an important step in the data mining process. The phrase “garbage in,
garbage out” is particularly applicable to data mining and machine learning projects. Data-
gathering methods are often loosely controlled, resulting inout-of-range values, impossible
data combinations (e.g., Sex: Male, Pregnant: Yes), missing values, etc. Analyzing data that
has not been carefully screened for such problems can produce misleading results. Thus, the
representation and quality of data is first and foremost before running an analysis.
ASSOCIATION RULE:
Apriori:
-The Apriori Algorithm is an influential algorithm for mining frequent itemsets for boolean
association rules.
-This algorithm may be considered to consist of two parts. In first part, those itemsets that
exceed the minimum support requirement are found. In second part, the association rules that
meet the minimum confidence requirement are found from the frequent itemsets. This
algorithm is resource intensive for large sets of transactions that have a large set of frequent
items.
Input:


D, a database of transactions.
Minimum confidence is 0.7.
Output: L, frequent itemsets in D
Method:
(1) L1= find_frequent_1-itemset(D);
(2) For(k=2;Lk-1≠Φ;k++){
(3) Ck=apriori.gen(Lk-1);
(4) For each transaction t ε D{//Scan D for counts
(5) Ct=subset(Ck,l); //get the subsets of t that are candidate
(6) For each candidate c ε Ct
(7) c.count++;
(8) }
(9) Lk={c ε Ck|c.count>= min_sup}
(10) }
(11) Return L=UkLk;
Procedure apriori.gen(Lk-1:frequent(k-1)-itemsets)
(1) For each itemset l1 ε Lk-1
(2) For each itemset l2 ε Lk-1
(3) If(l1[1]=l2[1])^(l1[2]=l2[2])^…^(l1[k-2]=l2[k-2])^(l1[k-1]<l2[k-1])then{
(4) C=l1 l2;//Join step: generate candidates
(5) If has.infrequent_subset(c,Lk-1) then
(6) Delete c;//prune step: remove unfruitful candidate
(7) Else add c to Ck;
(8) }
(9) Return Ck;
Procedure has_infrequent_subset(c:candidate k-itemset;
Lk-1:frequent(k-1)-itemsets);//use prior knowledge
(1) For each(k-1)-subset s of c
(2) If s ε Lk-1 then
(3) Return TRUE;
(4) Return FALSE;
OUTPUT:=== Run information ===
Scheme: weka.associations.Apriori -N 10 -T 0 -C 0.9 -D 0.05 -U 1.0 -M 0.1 -S -1.0 -c -1
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
=== Associator model (full training set) ===
Apriori
=======
Minimum support: 0.2 (5 instances)
Minimum metric <confidence>: 0.9
Number of cycles performed: 16
Generated sets of large itemsets:
Size of set of large itemsetsL(1): 11
Size of set of large itemsetsL(2): 21
Size of set of large itemsetsL(3): 6
Best rules found:
1. tear-prod-rate=reduced 12 ==> contact-lenses=none 12
conf:(1)
2. spectacle-prescrip=myope tear-prod-rate=reduced 6 ==> contact-lenses=none 6
conf:(1)
3. spectacle-prescrip=hypermetrope tear-prod-rate=reduced 6 ==> contact-lenses=none 6
conf:(1)
4. astigmatism=no tear-prod-rate=reduced 6 ==> contact-lenses=none 6
conf:(1)
5. astigmatism=yes tear-prod-rate=reduced 6 ==> contact-lenses=none 6
6. contact-lenses=soft 5 ==> astigmatism=no 5
conf:(1)
conf:(1)
7. contact-lenses=soft 5 ==> tear-prod-rate=normal 5
conf:(1)
8. tear-prod-rate=normal contact-lenses=soft 5 ==> astigmatism=no 5
conf:(1)
9. astigmatism=no contact-lenses=soft 5 ==> tear-prod-rate=normal 5
conf:(1)
10. contact-lenses=soft 5 ==> astigmatism=no tear-prod-rate=normal 5
conf:(1)
2.CLASSIFICATION:
(a) Naïve Bayers:This classification is quite different from the decision tree appraoach. In this, we have a
hypothesis that the given data belongs to a particular class.
Bayes theorem:P(A/B) = (P(B/A)P(A))/P(B)
Where, P(A)=Probability that A will Occur,
P(B)=Probability that B will Occur
P(B/A)=Probability that event B will occur when Event A has Already Occurred
Let us assume X as an Object to be classified by bayes Theorem.
To calculate: P(Ci/X) where Ci are different Classes.
Input: Training Datasets
Formula: P(Ci/X)= [P(X/Ci)P(Ci)]/P(X)
Where,
P(Ci/X):probability of object X belongigng to class Ci
P(X/Ci):probability of obtaining attribute values X if we know that it belongs to
class
Ci
P(Ci):probability of any object belonging to class Ci without any other information.
P(X):probability of Obtaining attributes values X whatever class the object belongs to.
Output:Assign X to the class that has the highest conditional probability.
OUTPUT:=== Run information ===
Scheme:
weka.classifiers.bayes.NaiveBayes
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
Test mode:
evaluate on training data
=== Classifier model (full training set) ===
Naive Bayes Classifier
Class
Attribute
soft hard none
(0.22) (0.19) (0.59)
==========================================
age
young
3.0
3.0
5.0
pre-presbyopic3.0 2.0
6.0
presbyopic
2.0 2.0
[total]
8.0
7.0
7.0 18.0
spectacle-prescrip
myope
3.0
hypermetrope4.0
[total]
7.0
4.0
2.0
8.0
9.0
6.0 17.0
astigmatism
no
6.0
1.0
8.0
yes
1.0
5.0
9.0
[total]
tear-prod-rate
7.0
6.0 17.0
reduced1.0
1.0 13.0
normal
6.0
5.0
[total]
4.0
7.0 6.0 17.0
Time taken to build model: 0 seconds
=== Evaluation on training set ===
=== Summary ===
Correctly Classified Instances
23
Incorrectly Classified Instances
95.8333 %
1
Kappa statistic
4.1667 %
0.925
Mean absolute error
0.1809
Root mean squared error
0.2357
Relative absolute error
49.1098 %
Root relative squared error
55.5663 %
Total Number of Instances
24
=== Detailed Accuracy By Class ===
TP Rate FP Rate Precision Recall F-Measure ROC Area Class
1
0.053
1
0
0.933 0
Weighted Avg.
0.833
1
1
1
0.909
1
0.933
0.958
1
0.966
0.011
1
soft
1
hard
1
none
0.965
0.958
0.96
1
=== Confusion Matrix ===
a b c <– classified as
5 0 0 | a = soft
0 4 0 | b = hard
1
0 14 | c = none
(b). J48 (Decision Tree):
This method results in a like tree structure where each node denotes a test on an attribute
value and each branch represents an outcome of the test.
Algorithm:
Generate decision tree. Generate a decision tree from the training tuples of data partition D.
Input:



Data partition, D, which is a set of training tuples and their associated class labels;
attribute list, the set of candidate attributes;
Attribute selection method, a procedure to determine the splitting criterion that “best”
partitions the data tuples into individual classes. This criterion consists of a splitting attribute
and, possibly, either a split point or splitting subset.
Output: A decision tree.
Method:
(1) create a node N;
(2) if tuples in D are all of the same class, C then
(3)
return N as a leaf node labeled with the class C;
(4) if attribute list is empty then
(5)
return N as a leaf node labeled with the majority class in D; // majority voting
(6) apply Attribute selection method(D, attribute list) to find the “best” splitting criterion;
(7) label node N with splitting criterion;
(8) if splitting attribute is discrete-valued and multiway splits allowed then
// not restricted to binary trees
(9) attribute list attribute list splitting attribute; // remove splitting attribute
(10)
i.
for each outcome j of splitting criterion
// partition the tuples and grow subtrees for each partition
(11)
let Djbe the set of data tuples in D satisfying outcome j; // a partition
(12)
if Djis empty then
(13)
attach a leaf labeled with the majority class in D to node N;
(14)
node N;
else attach the node returned by Generate decision tree(Dj, attribute list) to
1. endfor
(15)
return N;
OUTPUT:-
=== Run information ===
Scheme:
weka.classifiers.trees.J48 -C 0.25 -M 2
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
Test mode:
evaluate on training data
=== Classifier model (full training set) ===
J48 pruned tree
——————
tear-prod-rate = reduced: none (12.0)
tear-prod-rate = normal
| astigmatism = no: soft (6.0/1.0)
| astigmatism = yes
| | spectacle-prescrip = myope: hard (3.0)
| | spectacle-prescrip = hypermetrope: none (3.0/1.0)
Number of Leaves : 4
Size of the tree :7
Time taken to build model: 0 seconds
=== Evaluation on training set ===
=== Summary ===
Correctly Classified Instances
22
91.6667 %
2
8.3333 %
Incorrectly Classified Instances
Kappa statistic
0.8447
Mean absolute error
0.0833
Root mean squared error
0.2041
Relative absolute error
22.6257 %
Root relative squared error
48.1223 %
Total Number of Instances
24
=== Detailed Accuracy By Class ===
FP Rate FP Rate Precision Recall F-Measure ROC Area Class
1
0.053
0.75
0
0.933
0.111
0.833
1
1
0.909
0.974
soft
0.75
0.857
0.988
hard
0.933
Weighted Avg. 0.917
0.933
0.08
0.933
0.924
0.967
0.917
none
0.916
0.972
=== Confusion Matrix ===
a b c <– classified as
5 0 0 | a = soft
0 3 1 | b = hard
1
0 14 | c = none
(c) ID3 (Decision Tree):
ID3 algorithm is a supervised learner. It needs to have training data sets to make decisions.
The training set lists the attributes and their possible values. ID3 doesn’t deal with
continuous, numeric data which means we have to descretize them.
Algorithm:
1. Calculate the entropy of every attribute using the data set S.
Entropy H(S) is a measure of the amount of uncertainty in the (data) set S (i.e. entropy
characterizes the (data) set S).
Where,



- The current (data) set for which entropy is being calculated (changes every iteration of the
ID3 algorithm)
- Set of classes in
- The proportion of the number of elements in class to the number of elements in set
When , the set is perfectly classified (i.e. all elements in are of the same class)
2. Split the set into subsets using the attribute for which entropy is minimum (or, equivalently,
information gain is maximum).
3. Make a decision tree node containing that attribute.
4. Recurse on subsets using remaining attributes.
OUTPUT:=== Run information ===
Scheme:
weka.classifiers.trees.Id3
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
Test mode:
evaluate on training data
=== Classifier model (full training set) ===
Id3
tear-prod-rate = reduced: none
tear-prod-rate = normal
astigmatism = no
age = young: soft
age = pre-presbyopic: soft
age = presbyopic
spectacle-prescrip = myope: none
spectacle-prescrip = hypermetrope: soft
astigmatism = yes
spectacle-prescrip = myope: hard
spectacle-prescrip = hypermetrope
age = young: hard
age = pre-presbyopic: none
age = presbyopic: none
Time taken to build model: 0 seconds
=== Evaluation on training set ===
=== Summary ===
Correctly Classified Instances
24
100
0
0
Incorrectly Classified Instances
Kappa statistic
%
%
1
Mean absolute error
0
Root mean squared error
0
Relative absolute error
0
Root relative squared error
0
Total Number of Instances
24
%
%
=== Detailed Accuracy By Class ===
TP Rate FP Rate Precision Recall F-Measure ROC Area Class
1
0
1
1
0
1
1
0
1
Weighted Avg.
1
1
1
1
1
0
1
1
1
1
1
hard
1
1
soft
none
1
1
=== Confusion Matrix ===
a b c <– classified as
5 0 0 | a = soft
0 4 0 | b = hard
0 0 15 | c = none
3. CLUSTER DETECTION
(a)HierarchicalClusterer:
Algorithm:
Let X = {x1, x2, x3, …, xn} be the set of data points.
1) Begin with the disjoint clustering having level L(0) = 0 and sequence number m = 0.
2) Find the least distance pair of clusters in the current clustering, say pair (r), (s), according
to d[(r),(s)] = min d[(i),(j)] where the minimum is over all pairs of clusters in the current
clustering.
3)Increment the sequence number: m = m +1.Merge clusters (r) and (s) into a single cluster to
form the next clustering m. Set the level of this clustering to L(m) = d[(r),(s)].
4) Update the distance matrix, D, by deleting the rows and columns corresponding to clusters
(r) and (s) and adding a row and column corresponding to the newly formed cluster. The
distance between the new cluster, denoted (r,s) and old cluster(k) is defined in this way: d[(k),
(r,s)] = min (d[(k),(r)], d[(k),(s)]).
5)If all the data points are in one cluster then stop, else repeat from step 2)
OUTPUT:-
=== Run information ===
Scheme:
weka.clusterers.HierarchicalClusterer -N 2 -L SINGLE -P -A
“weka.core.EuclideanDistance -R first-last”
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
Test mode:
evaluate on training data
=== Model and evaluation on training set ===
Cluster 0
(((((((2.0:1,2.0:1):0,2.0:1):0,((2.0:1,2.0:1):0,2.0:1):0):0,((2.0:1,2.0:1):0,2.0:1):0):0,2.0:1):0,(((
2.0:1,(2.0:1,2.0:1):0):0,2.0:1):0,2.0:1):0):0.41421,((0.0:1,0.0:1):0,((0.0:1,0.0:1):0,0.0:1):0):0.
41421)
Cluster 1
(((1.0:1,1.0:1):0,1.0:1):0,1.0:1)
Clustered Instances
0
20 ( 83%)
1
4 ( 17%)
Simple KMeans:
Algorithm:
k-means. The k-means algorithm for partitioning, where each cluster’s
center is represented by the mean value of the objects in the cluster.
Input:
k: the number of clusters,
D: a data set containing n objects.
Output: A set of k clusters.
Method:
(1) arbitrarily choose k objects from D as the initial cluster centers;
(2) repeat
(3)
(re)assign each object to the cluster to which the object is the most similar,
based on the mean value of the objects in the cluster;
(4)
update the cluster means, i.e., calculate the mean value of the objects for
each cluster;
(1) until no change;
Output:=== Run information ===
Scheme:
weka.clusterers.SimpleKMeans -N 2 -A “weka.core.EuclideanDistance -R firstlast” -I 500 -S 10
Relation:
contact-lenses
Instances:
24
Attributes: 5
age
spectacle-prescrip
astigmatism
tear-prod-rate
contact-lenses
Test mode:
evaluate on training data
=== Model and evaluation on training set ===
kMeans
======
Number of iterations: 2
Within cluster sum of squared errors: 47.0
Missing values globally replaced with mean/mode
Cluster centroids:
Cluster#
Attribute
Full Data
(24)
(12)
(12)
0
1
=====================================================
age
young
youngyoung
spectacle-prescripmyopemyopemyope
astigmatism
tear-prod-rate
no
nono
reduced
normal
contact-lenses
none
soft
reduced
none
Clustered Instances
0
12 ( 50%)
1
12 ( 50%)
++++++++++++++++++++++++++++++++++++++++++++++
Topic:Multimedia Database
Creating table emp1
SQL> create table emp1
(Eno number(5),
Ename varchar2(50),
Eaddress varchar2(40),
photo BLOB )
Java Program to insert data into table emp
//MMDB1.java
Date:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
public class MMDB1 extends JFrame implements ActionListener {
JLabel label1;
JLabel lbleno;
JLabel lblename;
JLabel lbladdress;
JTextField txteno;
JTextField txtename;
JTextField txtaddress;
JTextField txtfilepath;
JButton insert;
JButton browse;
static String filename=null;
File file;
Connection con;
PreparedStatement ps;
static int fileno=0;
public MMDB1()
{
super(“Multimedia Database”);
label1=new JLabel(“Enter file path :”);
label1.setFont(new Font(“Verdana”,Font.PLAIN,12));
txtfilepath=new JTextField(25);
txtfilepath.setFont(new Font(“Verdana”,Font.PLAIN,12));
lbleno=new JLabel(“Enter the employee no”);
txteno=new JTextField(10);
lblename=new JLabel(“Enter the employee name”);
txtename=new JTextField(10);
lbladdress=new JLabel(“Enter the employee address”);
txtaddress=new JTextField(10);
browse=new JButton(“Browse”);
browse.setMnemonic(‘W’);
browse.setFont(new Font(“Verdana”,Font.PLAIN,12));
insert=new JButton(“Insert”);
insert.setMnemonic(‘I’);
insert.setFont(new Font(“Verdana”,Font.PLAIN,12));
getContentPane().setLayout(new FlowLayout());
getContentPane().add(lbleno);
getContentPane().add(txteno);
getContentPane().add(lblename);
getContentPane().add(txtename);
getContentPane().add(lbladdress);
getContentPane().add(txtaddress);
getContentPane().add(label1);
getContentPane().add(txtfilepath);
getContentPane().add(browse);
getContentPane().add(insert);
insert.addActionListener(this);
browse.addActionListener(this);
setSize(800,600);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource()==browse) {
open();
}
if (evt.getSource()==insert) {
Insertdata();
}
}
public static void main(String a[]) {
new MMDB1();
}
public void Insertdata() {
try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con = DriverManager.getConnection(“jdbc:odbc:MyProject”);
File(txtfilepath.getText());
FileInputStream fis=new FileInputStream(file);
file=new
ps=con.prepareStatement(“insert into emp1 values(?,?,?,?)”);
ps.setInt(1,Integer.parseInt(txteno.getText()));
ps.setString(2,txtename.getText());
ps.setString(3,txtaddress.getText());
ps.setBinaryStream(4,fis,(int)file.length());
ps.executeUpdate();
con.close();
System.out.println(“Inserted….”);
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
public void open() {
FileDialog fd=new FileDialog(this,”Select File”,FileDialog.LOAD);
fd.show();
if(fd.getFile()!=null){
txtfilepath.setText(fd.getDirectory()+fd.getFile());
filename=fd.getFile();
}
}
}
Java Program for Retrieving values from table emp1
//retriveimage1.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
public class retriveimage1 extends JFrame
{
static JComboBox imageid;
JLabel label1,label2;
JButton save;
static String Imagename=””;
String filename=””;
ImageIcon image;
JLabel imagelabel;
Connection con;
Statement statement;
byte[] imageBytes=new byte[2048];
public retriveimage1()
{
super(“Multimedia Database”);
label1=new JLabel(“Select Image No:”);
label1.setFont(new Font(“Verdana”,Font.PLAIN,12));
label2=new JLabel(“Your selected Image name is:”);
label2.setFont(new Font(“Verdana”,Font.PLAIN,12));
imageid =new JComboBox();
imageid.setFont(new Font(“Verdana”,Font.PLAIN,12));
imageid.setRequestFocusEnabled(true);
fillid();
imagelabel=new JLabel();
save=new JButton(“Save”);
save.setMnemonic(‘S’);
save.setFont(new Font(“Verdana”,Font.PLAIN,12));
getContentPane().setLayout(new FlowLayout());
getContentPane().add(label1);
getContentPane().add(imageid);
getContentPane().add(label2);
getContentPane().add(save);
getContentPane().add(imagelabel);
setSize(800,600);
setVisible(true);
imageid.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{try{
getImage();
}catch(Exception e){System.out.println(“Error”+e.getMessage());}
}
});
save.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
save();
}
});
}
public void fillid()
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con = DriverManager.getConnection(“jdbc:odbc:MyProject”);
statement=con.createStatement();
String SQL=”SELECT eno FROM emp1 ORDER BY eno”;
ResultSet resultset=statement.executeQuery(SQL);
while(resultset.next())
imageid.addItem(resultset.getString(1));
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public void getImage()
{
Imagename=””;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con = DriverManager.getConnection(“jdbc:odbc:MyProject”);
statement=con.createStatement();
String SQL=”SELECT * FROM emp1 WHERE eno=”+imageid.getSelectedItem()+””;
ResultSet resultset=statement.executeQuery(SQL);
while(resultset.next())
{
Imagename=resultset.getString(“ename”);
imageBytes=resultset.getBytes(“photo”);
}
image=new ImageIcon(imageBytes);
imagelabel.setIcon(image);
label2.setText(“Your selected Image name is : “+Imagename);
resultset.close();
statement.close();
con.close();
}
catch(Exception e)
{System.out.println(e.getMessage());}
}
public void save()
{
FileDialog fd=new FileDialog(this,”Save File”,FileDialog.SAVE);
fd.setFile(Imagename);
fd.show();
if(fd.getFile()!=null)
{
filename=fd.getDirectory()+fd.getFile();
try
{
FileOutputStream fos = new FileOutputStream
(new File(filename));
fos.write(imageBytes);
fos.close();
}
catch(Exception e)
{System.out.println(“File not saved…”);
}
}
}
public static void main(String args[])
{
new retriveimage1();
Output:
}}
Download