You are on page 1of 73

PROGRAM CODING: import java.io.

*; class rational1 { public rational1() { } public long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } } public class rational { public static void main(String args[]) throws IOException { rational1 r=new rational1(); long a,b,x,y; String str; DataInputStream in= new DataInputStream(System.in); System.out.println("Enter the value for A"); str=in.readLine(); a=Integer.parseInt(str); System.out.println("Enter the value for B"); str=in.readLine(); b=Integer.parseInt(str); long l=r.gcd(a,b); System.out.println(); System.out.println("The GCD of the number is:"+a); x=a/a; y=b/a; System.out.println(); System.out.println("The resultant value is :"+x+"/"+y); } }

OUTPUT:

PROGRAM CODING: import java. util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class DateExample { private static void DateExample() { Date date=new Date(); System.out.println("current Date and Time is:" +date); System.out.println(); System.out.println("Date object showing specific date time"); Date particulardate1=new Date(24L*60L*60L*1000L); Date particulardate2=new Date(0L); System.out.println(); System.out.println("First paricular Date:" +particulardate1); System.out.println("Second particular Date:" +particulardate2); System.out.println(); System.out.println("Demo of getTime() method returning milliseconds"); System.out.println(); Date strtime=new Date(); System.out.println("Start Time is:" +strtime); Date endtime=new Date(); System.out.println("End Time is: " +endtime); long elapsed_time=endtime.getTime()-strtime.getTime(); System.out.println("Elapsed Time is:" +elapsed_time+"milliseconds"); System.out.println(); Date chngdate=new Date(); System.out.println("Date before change is:" +chngdate); chngdate.setTime(24L*60L*60L*1000L); System.out.println("Now the changed time is" +chngdate); System.out.println(); } public static void main(String args[]) { System.out.println(); DateExample(); } }

OUTPUT:

PROGRAM CODING: class trydemo { public static void main(String args[]) { int d,a; try { d=0; a=42/d; System.out.println("this is line not executed"); } catch(ArithmeticException e) { System.out.println("caught"+e); } System.out.println("After try or catch block"); } }

OUTPUT:

PROGRAM CODING: class throwdemo { static void Throwone() throws NullPointerException { System.out.println("inside throwone"); throw new NullPointerException("demo"); } public static void main(String args[]) { try { Throwone(); } catch(NullPointerException e) { System.out.println("caughtException"+e); } } }

OUTPUT:

PROGRAM CODING: class finallydemo { static void procA(){ try {System.out.println("Inside procA"); throw new RuntimeException("Demo"); } finally{ System.out.println("procA's finally"); }} static void procB(){ try { System.out.println("Inside procB"); return; } finally{ System.out.println("procB's finally"); }} static void procC() { try { System.out.println("Inside procC"); } finally { System.out.println("procC's finally"); }} public static void main(String args[]){ try{ procA(); } catch(Exception e){ System.out.println("Exception caught"); } procB(); procC(); } }

OUTPUT:

PROGRAM CODING:

package lists;
public class ListNode { protected Object data; protected ListNode next; public ListNode (Object startingData) { data = startingData; next = null; } public ListNode (Object startingData, ListNode nextNode) { data = startingData; next = nextNode; } public Object getData () { return data; } public ListNode getNext () { return next; } public void setData (Object newData) { data = newData; } public void setNext (ListNode newNext) { next = newNext; } }

package lists;
import lists.ListNode; import java.lang.NullPointerException; import java.io.PrintWriter; public class ListLikeScheme { protected ListNode first; public ListLikeScheme () { first = null; } public boolean isNull() { return first == null; } public int length () { int i = 0; ListNode ptr = first; while (ptr != null) { i++; ptr = ptr.getNext(); } return i; }

public String toString() { String temp; if (first == null) temp = "nil"; else { temp = "(" + first.getData(); for (ListNode ptr=first.getNext(); ptr!=null; ptr=ptr.getNext()) temp = temp + " " + ptr.getData(); temp = temp + ")"; } return temp; } public int size () { return sizeKernel (first, 0); } private int sizeKernel (ListNode ptr, int count) { if (ptr == null) return count; else return sizeKernel (ptr.getNext(), (count + 1)); } public Object car () { if (isNull()) throw new NullPointerException("car applied to null list"); else return first.getData(); } public ListLikeScheme cdr () { if (isNull()) throw new NullPointerException("cdr applied to null list"); else { ListLikeScheme temp = new ListLikeScheme (); temp.first = first.getNext(); return temp; } } public void cons (Object newData, ListLikeScheme rest) { first = new ListNode (newData, rest.first); } public static void main (String argv[]) { PrintWriter out = new PrintWriter(System.out, true); ListLikeScheme A = new ListLikeScheme(); ListLikeScheme B = new ListLikeScheme(); ListLikeScheme C = new ListLikeScheme(); ListLikeScheme D = new ListLikeScheme(); C.cons ("nodeC", D); B.cons ("nodeB", C); A.cons ("nodeA", B); try { out.println ("List A: " + A); out.println (" length/size: " + A.length() + "\t" + A.size()); out.println (" null?: " + A.isNull()); out.println (" car: " + A.car());

out.println (" cdr: " + A.cdr()); out.println ("List B: " + B); out.println (" length/size: " + B.length() + "\t" + B.size()); out.println (" null?: " + B.isNull()); out.println (" car: " + B.car()); out.println (" cdr: " + B.cdr()); out.println ("List C: " + C); out.println (" length/size: " + C.length() + "\t" + C.size()); out.println (" null?: " + C.isNull()); out.println (" car: " + C.car()); out.println (" cdr: " + C.cdr()); out.println ("List D: " + D); out.println (" length/size: " + D.length() + "\t" + D.size()); out.println (" null?: " + D.isNull()); out.println (" car: " + D.car()); out.println (" cdr: " + D.cdr()); } catch (NullPointerException e) { out.println (e); } try { out.println (" cdr: " + D.cdr()); } catch (NullPointerException e) { out.println (e); } } }

OUTPUT: List A: (nodeA nodeB nodeC) length/size: 3 3 null?: false car: nodeA cdr: (nodeB nodeC) List B: (nodeB nodeC) length/size: 2 2 null?: false car: nodeB cdr: (nodeC) List C: (nodeC) length/size: 1 1 null?: false car: nodeC cdr: nil List D: nil length/size: 0 0 null?: true

PROGRAM CODING: class ArrayStack implements Stack { private Object [ ] theArray; private int topOfStack; private static final int DEFAULT_CAPACITY = 10; public ArrayStack( ) { theArray = new Object [ DEFAULT_CAPACITY ]; topOfStack = -1; } public boolean isEmpty() { return topOfStack == -1; } public void makeEmpty( ) { topOfStack = -1; } public Object top() { if(isEmpty()) throw new UnderflowException("ArrayStack top"); return theArray[ topOfStack ]; } public void pop( ) { if(isEmpty()) throw new UnderflowException( "ArrayStack pop"); topOfStack--; } public Object topAndPop() { if(isEmpty()) throw new UnderflowException( "ArrayStack topAndPop"); return theArray[topOfStack--]; } public void push(Object x) { if(topOfStack +1==theArray.length) doubleArray(); theArray[++topOfStack]=x; } private void doubleArray() { Object [] newArray;

newArray =new Object[theArray.length*2]; for(int i=0;i<theArray.length;i++) newArray[i] = theArray[i]; theArray = newArray; } } class LinkedListStack implements Stack { public LinkedListStack() { topOfStack = null; } public boolean isEmpty() { return topOfStack == null; } public void makeEmpty() { topOfStack = null; } public void push(Object x) { topOfStack = new ListNode(x,topOfStack); } public void pop() { if(isEmpty()) throw new UnderflowException("ListStack pop"); topOfStack = topOfStack.next; } public Object top() { if(isEmpty()) throw new UnderflowException("ListStack top"); return topOfStack.element; } public Object topAndPop() { if(isEmpty()) throw new UnderflowException("ListStack topAndPop"); Object topItem = topOfStack.element; topOfStack=topOfStack.next; return topItem; } private ListNode topOfStack; }

class ListNode { Object element; ListNode next; ListNode(Object theElement) { this (theElement,null); } public ListNode(Object theElement,ListNode n) { element = theElement; next = n; } } interface Stack { void push(Object x); void pop(); Object top(); Object topAndPop(); boolean isEmpty(); void makeEmpty(); } class StackTester { public static void main(String[] args) { System.out.println("**************"); System.out.println("Stack using Array & Linked List example"); System.out.println("**************"); ArrayStack arrayStack = new ArrayStack(); arrayStack.push(new String("a")); arrayStack.push(new String("b")); arrayStack.push(new String("c")); System.out.println("Stack[using array]elements->a,b,c"); System.out.println("Stack LIFO and Pop->"+arrayStack.topAndPop()); System.out.println("Stack LIFO->"+arrayStack.top()); arrayStack.pop(); try { arrayStack.pop(); arrayStack.topAndPop(); } catch(RuntimeException rte) {

System.err.println("Exception occured while Pop operation is happened on Stack[by using array]"); } System.out.println("\n\n*****************"); System.out.println("Stack using Linked List example"); System.out.println("******************"); LinkedListStack linkedListStack = new LinkedListStack(); linkedListStack.push(new Integer(10)); linkedListStack.push(new Integer(20)); linkedListStack.push(new Integer(30)); linkedListStack.push(new Integer(40)); System.out.println("Stack[using linked list elements->10,20,30,40"); System.out.println("Stack TOP->"+linkedListStack.top()); linkedListStack.pop(); System.out.println("Stack TOP after POP->"+linkedListStack.top()); linkedListStack.pop(); linkedListStack.pop(); linkedListStack.pop(); try { linkedListStack.pop(); } catch(RuntimeException rte) { System.err.println("Exception occured while POPoperation is happened on Stack[by using linked list]"); } } } class UnderflowException extends RuntimeException { public UnderflowException(String message) { super (message); } }

OUTPUT:

PROGRAM CODING: class vehicle { public int doors; public int seats; public int wheels; vehicle() { wheels=4; doors=4; seats=4; } } class car extends vehicle { public String toString() { return "This car has"+seats+"seats"+doors+"doors"+"and"+wheels+"wheels"; } } class motorcycle extends vehicle { motorcycle() { wheels=2; doors=0; seats=1; } void setseats(int num) { seats=num; } public String toString() { return "This motorcycle has"+seats+"seats"+doors+"doors"+"and"+wheels+"wheels"; } } class Truck extends vehicle { boolean ispickup; Truck() { ispickup=true; }

Truck(boolean apickup) { this(); ispickup=apickup; } Truck(int doors,int seats,int inwheels,boolean ispickup) { this.doors=doors; this.seats=seats; wheels=inwheels; this.ispickup=ispickup; } public String toString() { return "This"+(ispickup?"pickup":"truck") +"has"+seats+"seats"+doors+"doors"+"and"+wheels+"wheels"; } } class vehicleTest { public static void main(String args[]) { motorcycle mine=new motorcycle(); System.out.println(mine); car mine2=new car(); System.out.println(mine2); mine2.doors=2; System.out.println(mine2); Truck mine3=new Truck(); System.out.println(mine3); Truck mine4=new Truck(false); mine4.doors=2; System.out.println(mine4); } }

OUTPUT:

PROGRAM CODING:

class NewThread implements Runnable { Thread t; NewThread(){ t=new Thread(this,"DemoThread"); System.out.println("child thread:"+t); t.start(); } public void run(){ try { for(int i=5;i>0;i--) { System.out.println("child thread:"+ i); Thread.sleep(500); }} catch(InterruptedException e) { System.out.println("child interrupted"); } System.out.println("Existing child thread"); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); try{ for(int i=5;i>0;i--){ System.out.println("main thread:"+ i); Thread.sleep(1000); }} catch(InterruptedException e) { System.out.println("main thread Interrupted"); } System.out.println("main thread Existing"); }}

OUTPUT:

PROGRAM CODING: class NewThread extends Thread { NewThread(){ super("Demothread"); System.out.println("childthread:"+this); start(); } public void run(){ try { for(int i=5;i>0;i--){ System.out.println("childthread:"+i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("child interrupted"); } System.out.println("Existing childthread"); }} class ExtendedThread { public static void main(String args[]) { new NewThread(); try{ for(int i=5;i>0;i--){ System.out.println("main thread"); Thread.sleep(12345); }} catch(InterruptedException e) { System.out.println("main thread Interrupted"); } System.out.println("main thread Existing"); } }

OUTPUT:

PROGRAM CODING: import java.io.*; public class Currency { public static void main(String args[]) { Dollar dr=new Dollar('$',40); dr.printDollar(); Rupee re=new Rupee("Rs.",50); re.printRupee(); try { File f=new File("rd.txt"); FileOutputStream fos=new FileOutputStream(f); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(dr); oos.writeObject(re); oos.flush(); oos.close(); ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt")); Dollar d1; d1=(Dollar)ois.readObject(); d1.printDollar(); Rupee r1; r1=(Rupee)ois.readObject(); r1.printRupee(); ois.close(); } catch(Exception e) { } } } class Dollar implements Serializable { private float dol; private char sym; public Dollar(char sm,float doll) { sym=sm; dol=doll; } void printDollar() { System.out.print(sym);

System.out.println(dol); } } class Rupee implements Serializable { private String sym; private float rs; public Rupee(String sm,float rup) { sym=sm; rs=rup; } void printRupee() { System.out.print(sym); System.out.println(rs); } }

OUTPUT:

PROGRAM CODING: import java.awt.*; import java.awt.event.*; class CalcFrame extends Frame { CalcFrame( String str) { super(str); addWindowListener(new WindowAdapter() { public void windowClosing (WindowEvent we) { System.exit(0); } }); } } public class Calculator implements ActionListener, ItemListener { CalcFrame fr; MenuBar mb; Menu view, font, about; MenuItem bold, regular, author; CheckboxMenuItem basic, scientific; CheckboxGroup cbg; Checkbox radians, degrees; TextField display; Button key[] = new Button[20]; Button clearAll, clearEntry, round; Button scientificKey[] = new Button[10]; boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed; boolean divideButtonPressed, decimalPointPressed, powerButtonPressed; boolean roundButtonPressed = false; double initialNumber; double currentNumber = 0; int decimalPlaces = 0; public static void main (String args[]) { Calculator calc = new Calculator(); calc.makeCalculator(); } public void makeCalculator() { final int BWIDTH = 25; final int BHEIGHT = 25; int count =1; fr = new CalcFrame("Basic Calculator"); fr.setSize(200,270); fr.setBackground(Color.blue);; mb = new MenuBar(); view = new Menu("View"); font = new Menu ("Font"); about = new Menu("About"); basic = new CheckboxMenuItem("Basic",true); basic.addItemListener(this); scientific = new CheckboxMenuItem("Scientific"); scientific.addItemListener(this);

bold = new MenuItem("Arial Bold"); bold.addActionListener(this); regular = new MenuItem("Arial Regular"); regular.addActionListener(this); author = new MenuItem("Author"); author.addActionListener(this); view.add(basic); view.add(scientific); font.add(bold); font.add(regular); about.add(author); mb.add(view); mb.add(font); mb.add(about); fr.setMenuBar(mb); fr.setLayout(null); for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { key[count] = new Button(Integer.toString(count)); key[count].addActionListener(this); key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT); key[count].setBackground(Color.yellow); fr.add(key[count++]); } } key[0] = new Button("0"); key[0].addActionListener(this); key[0].setBounds(30,210,BWIDTH,BHEIGHT); key[0].setBackground(Color.yellow); fr.add(key[0]); key[10] = new Button("."); key[10].addActionListener(this); key[10].setBounds(60,210,BWIDTH,BHEIGHT); key[10].setBackground(Color.yellow); fr.add(key[10]); key[11] = new Button("="); key[11].addActionListener(this); key[11].setBounds(90,210,BWIDTH,BHEIGHT); key[11].setBackground(Color.yellow); fr.add(key[11]); key[12] = new Button("*"); key[12].addActionListener(this); key[12].setBounds(120,120,BWIDTH,BHEIGHT); key[12].setBackground(Color.yellow); fr.add(key[12]); key[13] = new Button("/"); key[13].addActionListener(this); key[13].setBounds(120,150,BWIDTH,BHEIGHT); key[13].setBackground(Color.yellow); fr.add(key[13]); key[14] = new Button("+");

key[14].addActionListener(this); key[14].setBounds(120,180,BWIDTH,BHEIGHT); key[14].setBackground(Color.yellow); fr.add(key[14]); key[15] = new Button("-"); key[15].addActionListener(this); key[15].setBounds(120,210,BWIDTH,BHEIGHT); key[15].setBackground(Color.yellow); fr.add(key[15]); key[16] = new Button("1/x"); key[16].addActionListener(this); key[16].setBounds(150,120,BWIDTH,BHEIGHT); key[16].setBackground(Color.yellow); fr.add(key[16]); key[17] = new Button("x^n"); key[17].addActionListener(this); key[17].setBounds(150,150,BWIDTH,BHEIGHT); key[17].setBackground(Color.yellow); fr.add(key[17]); key[18] = new Button("+/-"); key[18].addActionListener(this); key[18].setBounds(150,180,BWIDTH,BHEIGHT); key[18].setBackground(Color.yellow); fr.add(key[18]); key[19] = new Button("x!"); key[19].addActionListener(this); key[19].setBounds(150,210,BWIDTH,BHEIGHT); key[19].setBackground(Color.yellow); fr.add(key[19]); clearAll = new Button("CA"); clearAll.addActionListener(this); clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT); clearAll.setBackground(Color.yellow); fr.add(clearAll); clearEntry = new Button("CE"); clearEntry.addActionListener(this); clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT); clearEntry.setBackground(Color.yellow); fr.add(clearEntry); round = new Button("Round"); round.addActionListener(this); round.setBounds(130, 240, BWIDTH+20, BHEIGHT); round.setBackground(Color.yellow); fr.add(round); display = new TextField("0"); display.setBounds(30,90,150,20); display.setBackground(Color.white); scientificKey[0] = new Button("Sin"); scientificKey[0].addActionListener(this); scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT); scientificKey[0].setVisible(false);

scientificKey[0].setBackground(Color.yellow); fr.add(scientificKey[0]); scientificKey[1] = new Button("Cos"); scientificKey[1].addActionListener(this); scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT); scientificKey[1].setBackground(Color.yellow); scientificKey[1].setVisible(false); fr.add(scientificKey[1]); scientificKey[2] = new Button("Tan"); scientificKey[2].addActionListener(this); scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT); scientificKey[2].setBackground(Color.yellow); scientificKey[2].setVisible(false); fr.add(scientificKey[2]); scientificKey[3] = new Button("Pi"); scientificKey[3].addActionListener(this); scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT); scientificKey[3].setBackground(Color.yellow); scientificKey[3].setVisible(false); fr.add(scientificKey[3]); scientificKey[4] = new Button("aSin"); scientificKey[4].addActionListener(this); scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT); scientificKey[4].setBackground(Color.yellow); scientificKey[4].setVisible(false); fr.add(scientificKey[4]); scientificKey[5] = new Button("aCos"); scientificKey[5].addActionListener(this); scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT); scientificKey[5].setBackground(Color.yellow); scientificKey[5].setVisible(false); fr.add(scientificKey[5]); scientificKey[6] = new Button("aTan"); scientificKey[6].addActionListener(this); scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT); scientificKey[6].setBackground(Color.yellow); scientificKey[6].setVisible(false); fr.add(scientificKey[6]); scientificKey[7] = new Button("E"); scientificKey[7].addActionListener(this); scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT); scientificKey[7].setBackground(Color.yellow); scientificKey[7].setVisible(false); fr.add(scientificKey[7]); scientificKey[8] = new Button("todeg"); scientificKey[8].addActionListener(this); scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT); scientificKey[8].setBackground(Color.yellow); scientificKey[8].setVisible(false); fr.add(scientificKey[8]); scientificKey[9] = new Button("torad");

scientificKey[9].addActionListener(this); scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT); scientificKey[9].setBackground(Color.yellow); scientificKey[9].setVisible(false); fr.add(scientificKey[9]); cbg = new CheckboxGroup(); degrees = new Checkbox("Degrees", cbg, true); radians = new Checkbox("Radians", cbg, false); degrees.addItemListener(this); radians.addItemListener(this); degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT); radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT); degrees.setVisible(false); radians.setVisible(false); fr.add(degrees); fr.add(radians); fr.add(display); fr.setVisible(true); } public void actionPerformed(ActionEvent ae) { String buttonText = ae.getActionCommand(); double displayNumber = Double.valueOf(display.getText()).doubleValue(); if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) { if(decimalPointPressed) { for (int i=1;i <=decimalPlaces; ++i) currentNumber *= 10; currentNumber +=(int)buttonText.charAt(0)- (int)'0'; for (int i=1;i <=decimalPlaces; ++i) { currentNumber /=10; } ++decimalPlaces; display.setText(Double.toString(currentNumber)); } else if (roundButtonPressed) { int decPlaces = (int)buttonText.charAt(0) - (int)'0'; for (int i=0; i< decPlaces; ++i) displayNumber *=10; displayNumber = Math.round(displayNumber); for (int i = 0; i < decPlaces; ++i) { displayNumber /=10; } display.setText(Double.toString(displayNumber)); roundButtonPressed = false; } else { currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0'; display.setText(Integer.toString((int)currentNumber)); } } if(buttonText == "+") { addButtonPressed = true;

initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } if (buttonText == "-") { subtractButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } if (buttonText == "/") { divideButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } if (buttonText == "*") { multiplyButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } if (buttonText == "1/x") { display.setText(reciprocal(displayNumber)); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "+/-") { display.setText(changeSign(displayNumber)); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "x!") { display.setText(factorial(displayNumber)); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "x^n") { powerButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } if (buttonText == "Sin") { if (degrees.getState()) display.setText(Double.toString(Math.sin(Math.PI * displayNumber/180))); else { display.setText(Double.toString(Math.sin(displayNumber))); currentNumber = 0; decimalPointPressed = false; }

} if (buttonText == "Cos") { if (degrees.getState()) display.setText(Double.toString(Math.cos(Math.PI * displayNumber/180))); else{ display.setText(Double.toString(Math.cos(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "Tan") { if (degrees.getState()) display.setText(Double.toString(Math.tan(Math.PI * displayNumber/180))); else { display.setText(Double.toString(Math.tan(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "aSin") { if (degrees.getState()) display.setText(Double.toString(Math.asin(displayNumber)* 180/Math.PI )); else { display.setText(Double.toString(Math.asin(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "aCos") { if (degrees.getState()) display.setText(Double.toString(Math.acos(displayNumber)* 180/Math.PI )); else { display.setText(Double.toString(Math.acos(displayNumber))); currentNumber = 0; decimalPointPressed = false; }} if (buttonText == "aTan") { if (degrees.getState()) display.setText(Double.toString(Math.atan(displayNumber)* 180/Math.PI )); else { display.setText(Double.toString(Math.atan(displayNumber))); currentNumber = 0; decimalPointPressed = false; }} if (buttonText == "todeg") display.setText(Double.toString(Math.toDegrees(displayNumber))); if (buttonText == "torad") display.setText(Double.toString(Math.toRadians(displayNumber))); if (buttonText == "Pi") { display.setText(Double.toString(Math.PI)); currentNumber =0;

decimalPointPressed = false; } if (buttonText == "Round") roundButtonPressed = true; if (buttonText == ".") { String displayedNumber = display.getText(); boolean decimalPointFound = false; int i; decimalPointPressed = true; for (i =0; i < displayedNumber.length(); ++i) { if(displayedNumber.charAt(i) == '.') { decimalPointFound = true; continue; }} if (!decimalPointFound) decimalPlaces = 1; } if(buttonText == "CA"){ resetAllButtons(); display.setText("0"); currentNumber = 0; } if (buttonText == "CE") { display.setText("0"); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "E") { display.setText(Double.toString(Math.E)); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "=") { currentNumber = 0; if(addButtonPressed) display.setText(Double.toString(initialNumber + displayNumber)); if(subtractButtonPressed) display.setText(Double.toString(initialNumber - displayNumber)); if (divideButtonPressed) { if(displayNumber == 0) { MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero."); mb.show(); } else display.setText(Double.toString(initialNumber/displayNumber)); } if(multiplyButtonPressed) display.setText(Double.toString(initialNumber * displayNumber)); if (powerButtonPressed) display.setText(power(initialNumber, displayNumber)); resetAllButtons();

} if (buttonText == "Arial Regular") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.PLAIN, 12)); } if (buttonText == "Arial Bold") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.BOLD, 12)); } if (buttonText == "Author") { MessageBox mb = new MessageBox ( fr, "Calculator ver 1.0 beta ", true, "Author: CsE Rockers."); mb.show(); }} public void itemStateChanged(ItemEvent ie) { if (ie.getItem() == "Basic") { basic.setState(true); scientific.setState(false); fr.setTitle("Basic Calculator"); fr.setSize(200,270); if (scientificKey[0].isVisible()) { for (int i=0; i < 8; ++i) scientificKey[i].setVisible(false); radians.setVisible(false); degrees.setVisible(false); } } if (ie.getItem() == "Scientific") { basic.setState(false); scientific.setState(true); fr.setTitle("Scientific Calculator"); fr.setSize(270,270); if (!scientificKey[0].isVisible()) { for (int i=0; i < 10; ++i) scientificKey[i].setVisible(true); radians.setVisible(true); degrees.setVisible(true); }}} public void resetAllButtons() { addButtonPressed = false; subtractButtonPressed = false; multiplyButtonPressed = false; divideButtonPressed = false; decimalPointPressed = false; powerButtonPressed = false; roundButtonPressed = false; } public String factorial(double num) { int theNum = (int)num; if (theNum < 1) {

MessageBox mb = new MessageBox (fr, "Facorial Error", true,"Cannot find the factorial of numbers less than 1."); mb.show(); return ("0"); } else { for (int i=(theNum -1); i > 1; --i) theNum *= i; return Integer.toString(theNum); }} public String reciprocal(double num) { if (num ==0) { MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,"Cannot find the reciprocal of 0"); mb.show(); } else num = 1/num; return Double.toString(num); } public String power (double base, double index) { return Double.toString(Math.pow(base, index)); } public String changeSign(double num) { return Double.toString(-num); }} class MessageBox extends Dialog implements ActionListener { Button ok; MessageBox(Frame f, String title, boolean mode, String message) { super(f, title, mode); Panel centrePanel = new Panel(); Label lbl = new Label(message); centrePanel.add(lbl); add(centrePanel, "Center"); Panel southPanel = new Panel(); ok = new Button ("OK"); ok.addActionListener(this); southPanel.add(ok); add(southPanel, "South"); pack(); addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent we) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { dispose();
}}

OUTPUT:

PROGRAM CODING: class prime extends Thread { public int x1; public long[] f = new long[50000]; public synchronized void run() { int count=0; System.out.println("The prime numbers are"); for(long j=2;j<=100000;j++) { count=0; for(int i=(int) (j - 1);i>=2;i--) { if(j%i==0) { count++; break; } } if(count==0) { f[x1]= j; System.out.println(f[x1]); x1++; } System.out.println(j); } } } class fibonacci extends Thread { public int x2; public long[] f = new long[25]; //creates array length of 46 public synchronized void run() { f[0] = 1; //first item in array (computer starts counting at 0 not 1) f[1] = 1; //second item in array x2=0; //declares x of type int (integer) System.out.println("The fibonacci series is"); System.out.print(f[0] + "\n" + f[1] + "\n"); //outputs the first 2 elements in array f for(x2=2; x2<=24; x2++) { f[x2] = f[x2-1] + f[x2-2];//calculates next element in array System.out.println(f[x2]); //output next elements in array 2-4 } } } class MultipleThread {

public static void main(String args[]) { int []f=new int[25]; int x=0,x1=0,x2=0; prime pr =new prime(); fibonacci fb=new fibonacci(); try { pr.start(); fibonacci.sleep(100000); System.out.println("Prime Thread is terminating now"); System.out.println("Fibonacci Thread is Starting now "); fb.start(); Thread.sleep(1000); System.out.println("Fibonacci Thread is ends now "); x=0; for(x2=0;x2<25;x2++) { for(x1=0;x1<=9591;x1++) { if(pr.f[x1]==fb.f[x2]) { f[x]=(int) fb.f[x2]; System.out.println(f[x]); x++; break; } } } } catch(Exception e) { System.out.println("Thread problem"); } } }

OUTPUT:

PROGRAM CODING: import java.io.*; import java.sql.*; class javadb { public static void main(String args[]) { ResultSet rs = null; String stud_no = ""; String choice = ""; DataInputStream dis = new DataInputStream(System.in); try { display_line(); System.out.println("\n"); System.out.println("\t\tEnter your choice :"); System.out.println("\t\tDisplay Single Recored (1) :"); System.out.println("\t\tDisplay All Records (2) :"); choice = dis.readLine(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:stud"); Statement stmt = con.createStatement(); if (choice.equals("1")) { System.out.println("\n"); System.out.println("\t\tEntered the choice is one") System.out.println("\t\t Enter the student register number :"); stud_no = dis.readLine(); int j = Integer.parseInt(stud_no); rs = stmt.executeQuery("select * from student where regno=" + j + ""); }if (choice.equals("2")) { System.out.println("\t\tEntered the choice is two") rs = stmt.executeQuery("select * from student"); } while (rs.next()) { System.out.println(rs.getString(1)) System.out.println(rs.getString(2)); } display_line(); } catch (Exception e) { System.out.println(e); }}public static void display_line() { char ch = '*'; int i = 0; for (i = 0; i < 75; i++) { System.out.print(ch); }}}

OUTPUT: STUDENT.mdb

PROGRAM CODING: import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; import javax.swing.JPopupMenu; import com.sun.java.swing.plaf.motif.MotifLookAndFeel; public class ProjectLibrary extends JFrame implements ActionListener { JTextField id,phno,name,add,city,padd,eadd,class1,shift,progress,date; JTextField bookTF,authorTF,priceTF,bcodeTF; JTextField cdcodeTF,cdtitleTF,cdisbnTF,cdeditionTF,cdpubTF; Container c; JButton search,save,delete,exit,update; JButton searBook,saveNow,update1; JButton cdsearch,cdsave,cddelete,cdexit,cdupdate; JLabel cdlogo,cdcode,cdtitle,cdisbn,cdedit,cdpub; JOptionPane jp = new JOptionPane(); JMenuBar menuBar,menuBar1; JMenu menu1,menu2; JMenuItem menuItemN,menuItemB,menuItemC,menuItemH,menuItemA,menuIte mE; Cursor cur; public ProjectLibrary() { super("Library Record System"); c = getContentPane(); c.setBackground(new Color(14,58,119)); c.setLayout(null); setBounds(0,0,850,590); setFont(new Font("verdana",3,14)); cur = new Cursor(Cursor.CROSSHAIR_CURSOR); setCursor(cur); ImageIcon coll = new ImageIcon("collicon.gif"); JLabel LogoColl = new JLabel(coll); menuBar = new JMenuBar(); menu1 = new JMenu("Library"); menu1.setBackground(Color.white); menu1.setMnemonic('L'); menu2 = new JMenu("Help"); menu2.setMnemonic('H'); menu2.setBackground(Color.white);

menuItemN = new JMenuItem("New",new ImageIcon("NEW.GIF")); menuItemN.setBackground(Color.white); menuItemN.setMnemonic('N'); menuItemB = new JMenuItem("Books",new ImageIcon("b.gif")); menuItemB.setBackground(Color.white); menuItemB.setMnemonic('B'); menuItemC = new JMenuItem("CD's",new ImageIcon("cd.PNG"));menuItemC.setBackground(Color.white); menuItemC.setMnemonic('C'); menuItemE = new JMenuItem("Exit",new ImageIcon("Exit.PNG")); menuItemE.setBackground(Color.white); menuItemE.setMnemonic('E'); menuItemH = new JMenuItem("Help library",new ImageIcon("help.gif")); menuItemH.setBackground(Color.white); menuItemH.setMnemonic('E'); menuItemA = new JMenuItem("About LRS"); setJMenuBar(menuBar); JLabel lDate = new JLabel("Issue Of Date :"); lDate.setForeground(Color.white); JLabel ph = new JLabel("Enter Phone Number :"); ph.setForeground(Color.white); JLabel lname = new JLabel("Student's Name :"); lname.setForeground(Color.white); JLabel address = new JLabel("Student's Address :"); address.setForeground(Color.white); JLabel lid = new JLabel("Book Code"); lid.setForeground(Color.white); JLabel lcity = new JLabel("City"); lcity.setForeground(Color.white); JLabel pad = new JLabel("Permenent Address"); pad.setForeground(Color.white); JLabel leadd = new JLabel("Email Address"); leadd.setForeground(Color.white); JLabel lclass = new JLabel("Class"); lclass.setForeground(Color.white); JLabel lshift = new JLabel("Shift"); lshift.setForeground(Color.white); JLabel lprogress = new JLabel("Progress"); lprogress.setForeground(Color.white); ImageIcon next = new ImageIcon("next.gif"); JLabel next1 = new JLabel(next); ImageIcon previous = new ImageIcon("Back.gif"); JLabel previous1 = new JLabel(previous); ImageIcon background = new ImageIcon("backg.jpg"); JLabel img = new JLabel(background); ImageIcon college = new ImageIcon("Movie1.PNG"); JLabel colLogo = new JLabel(college); ImageIcon LineStraight = new ImageIcon("lineh.gif"); JLabel Line = new JLabel(LineStraight); date = new JTextField();

date.setForeground(Color.black); date.setBackground(Color.white); phno = new JTextField(); phno.setForeground(Color.black); phno.setBackground(Color.white); name = new JTextField(); name.setForeground(Color.black); name.setBackground(Color.white); add = new JTextField(); add.setForeground(Color.black); add.setBackground(Color.white); eadd = new JTextField(); eadd.setForeground(Color.black); eadd.setBackground(Color.white); city = new JTextField(); city.setForeground(Color.black); city.setBackground(Color.white); padd = new JTextField(); padd.setForeground(Color.black); padd.setBackground(Color.white); id = new JTextField(); id.setForeground(Color.black); id.setBackground(Color.white); class1 = new JTextField(); class1.setForeground(Color.black); class1.setBackground(Color.white); shift = new JTextField(); shift.setForeground(Color.black); shift.setBackground(Color.white); progress = new JTextField(); progress.setForeground(Color.black); progress.setBackground(Color.white); search = new JButton("Search",new ImageIcon("search.gif")); search.setForeground(Color.white); search.setBackground(Color.pink); save = new JButton("Save", new ImageIcon("Save.gif")); save.setForeground(Color.white); save.setBackground(Color.pink); delete = new JButton("Delete", new ImageIcon("remove.gif")); delete.setForeground(Color.white); delete.setBackground(Color.pink); exit = new JButton("Exit", new ImageIcon("EXIT.PNG")); exit.setForeground(Color.white); exit.setBackground(Color.pink); update = new JButton("Update", new ImageIcon("update.gif")); update.setForeground(Color.white); update.setBackground(Color.pink); search.setToolTipText("Search the record"); save.setToolTipText("Save the record"); delete.setToolTipText("Delete the record"); exit.setToolTipText("Exit from the library");

update.setToolTipText("Update the record"); lDate.setBounds(80,135,670,150); LogoColl.setBounds(380,20,670,150); lid.setBounds(80,240,150,20); ph.setBounds(400,245,150,20); lname.setBounds(80,285,150,20); address.setBounds(400,290,150,20); lcity.setBounds(400,330,150,20); pad.setBounds(400,375,150,20); leadd.setBounds(400,415,150,20); lclass.setBounds(80,330,150,20); lshift.setBounds(80,380,150,20); lprogress.setBounds(80,415,150,20); next1.setBounds(650,478,180,54); previous1.setBounds(10,478,190,54); img.setBounds(90,100,20,40); colLogo.setBounds(3,0,790,142); Line.setBounds(2,2,48,1000); date.setBounds(220,190,152,26); id.setBounds(220,235,152,26); phno.setBounds(550,245,152,26); name.setBounds(220,280,152,26); add.setBounds(550,290,152,26); city.setBounds(550,330,152,26); padd.setBounds(550,370,152,26); eadd.setBounds(550,410,152,26); class1.setBounds(220,325,152,26); shift.setBounds(220,370,152,26); progress.setBounds(220,415,152,26); search.setBounds(160,490,105,30); save.setBounds(270,490,90,30); delete.setBounds(363,490,95,30); update.setBounds(460,490,110,30); exit.setBounds(575,490,95,30); menu1.add(menuItemN); menu1.add(menuItemB); menu1.add(menuItemC); menu1.add(menuItemE); menuBar.add(menu1); menu2.add(menuItemH); menu2.add(menuItemA); menuBar.add(menu2); save.addActionListener(this); search.addActionListener(this); delete.addActionListener(this); update.addActionListener(this); exit.addActionListener(this); menuItemN.addActionListener(this); menuItemB.addActionListener(this); menuItemC.addActionListener(this);

menuItemH.addActionListener(this); menuItemA.addActionListener(this); menuItemE.addActionListener(this); c.add(search); c.add(save ); c.add(delete); c.add(exit); c.add(update); c.add(LogoColl); c.add(lDate); c.add(ph); c.add(lname); c.add(address); c.add(lid); c.add(lcity); c.add(pad); c.add(leadd); c.add(lclass); c.add(lshift); c.add(lprogress); c.add(next1); c.add(previous1); c.add(img); c.add(colLogo); c.add(date); c.add(phno); c.add(name); c.add(add); c.add(city); c.add(padd); c.add(id); c.add(eadd); c.add(class1); c.add(progress); c.add(shift); c.add(Line); next1.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent me){ int a = Integer.parseInt(id.getText()); a++; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select * from Directory where Id="+a); while(rs.next()){ date.setText(rs.getString("DateToday")); id.setText(rs.getString("Id"));

name.setText(rs.getString("Name")); add.setText(rs.getString("Address")); class1.setText(rs.getString("Class")); progress.setText(rs.getString("Progress")); shift.setText(rs.getString("Shift")); city.setText(rs.getString("City")); padd.setText(rs.getString("Permenent_Address")); phno.setText(rs.getString("PhoneNo")); eadd.setText(rs.getString("eaddress")); } c.close(); st.close(); } catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception"); } catch(SQLException sql) { System.out.println(sql); }}}); previous1.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { int a = Integer.parseInt(id.getText()); a--; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select * from Directory where Id="+a); while(rs.next()) date.setText(rs.getString("DateToday")); id.setText(rs.getString("Id")); name.setText(rs.getString("Name")); add.setText(rs.getString("Address")); class1.setText(rs.getString("Class")); progress.setText(rs.getString("Progress")); shift.setText(rs.getString("Shift")); city.setText(rs.getString("City")); padd.setText(rs.getString("Permenent_Address")); phno.setText(rs.getString("PhoneNo")); eadd.setText(rs.getString("eaddress")); } c.close(); st.close();

} catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception"); } catch(SQLException sql) { System.out.println(sql); }}}); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent ae) { String str1=(String)ae.getActionCommand(); Object source = ae.getSource(); if(source==menuItemA) { JFrame aboutus = new JFrame("About us"); aboutus.setSize(700,500); aboutus.getContentPane().setLayout(null); ImageIcon design = new ImageIcon("about.png"); JLabel cover = new JLabel(design); aboutus.getContentPane().add(cover); cover.setBounds(5,0,685,500); aboutus.setVisible(true); } if(source==menuItemN) { id.setEditable(true); phno.setEditable(true); name.setEditable(true); add.setEditable(true); city.setEditable(true); padd.setEditable(true); eadd.setEditable(true); class1.setEditable(true); shift.setEditable(true); progress.setEditable(true); date.setEditable(true); id.setText(null); phno.setText(null); name.setText(null); add.setText(null); city.setText(null); padd.setText(null); eadd.setText(null); class1.setText(null); shift.setText(null); progress.setText(null);

date.setText(null); } if(source==menuItemB) { JFrame book=new JFrame("Book's available in library"); book.setSize(660,560); book.getContentPane().setLayout(null); book.getContentPane().setBackground(new Color(14,58,119)); book.getContentPane().setForeground(Color.white); book.setResizable(false); JLabel BookName = new JLabel("Book Name:"); book.getContentPane().add(BookName); JLabel AuthorName = new JLabel("Author Name:"); book.getContentPane().add(AuthorName); JLabel Pri = new JLabel("Price:"); book.getContentPane().add(Pri); JLabel Bcode = new JLabel("Book Code:"); book.getContentPane().add(Bcode); bookTF = new JTextField(10); book.getContentPane().add(bookTF); authorTF = new JTextField(10); book.getContentPane().add(authorTF); priceTF = new JTextField(5); book.getContentPane().add(priceTF); bcodeTF = new JTextField(5); book.getContentPane().add(bcodeTF); ImageIcon logobook = new ImageIcon("logoBook.jpg"); JLabel logoBook = new JLabel(logobook); book.getContentPane().add(logoBook); searBook = new JButton("Search", new ImageIcon("SEARCH.PNG")); book.getContentPane().add(searBook); saveNow = new JButton("Save", new ImageIcon("SAVE.PNG")); book.getContentPane().add(saveNow); update1 = new JButton("Update", new ImageIcon("UPDATE.PNG")); book.getContentPane().add(update1); logoBook.setBounds(0,0,650,171); Bcode.setBounds(33,200,112,30); BookName.setBounds(33,250,112,30); AuthorName.setBounds(30,310,112,30); Pri.setBounds(31,370,112,30); bcodeTF.setBounds(123,200,100,20); bookTF.setBounds(123,255,262,20); authorTF.setBounds(123,315,262,20); priceTF.setBounds(123,375,100,20); saveNow.setBounds(280,500,111,30); update1.setBounds(400,500,111,30); searBook.setBounds(160,500,111,30); saveNow.addActionListener(this); update1.addActionListener(this); searBook.addActionListener(this);

book.setVisible(true); } if(source==menuItemE) { System.exit(0); jp = new JOptionPane(); } if(source==saveNow) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps = c.prepareStatement("Insert into Book values(?,?,?,?)"); ps.setString(1,bcodeTF.getText()); ps.setString(2,bookTF.getText()); ps.setString(3,authorTF.getText()); ps.setString(4,priceTF.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Inserted Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) {System.out.println("Cnf Exception");} catch(SQLException sql) {jp.showMessageDialog(this,"Record Already Exists","EXCEPTION",jp.ERROR_MESSAGE);} } if(source==update1) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps=c.prepareStatement ("Update Book set BookName=? , AuthorName=? , Price=? where BookCode="+bcodeTF.getText() ); ps.setString(1,bookTF.getText()); ps.setString(2,authorTF.getText()); ps.setInt(3,Integer.parseInt(priceTF.getText())); ps.executeUpdate(); jp.showMessageDialog(this,"Record Updated Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close();

} catch(ClassNotFoundException cnf) {System.out.println("Cnf Exception");} catch(SQLException sql) {jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE);} } if(source==menuItemC) { JFrame cd=new JFrame("CD's available in library"); cd.setSize(510,540); cd.getContentPane().setLayout(null); cd.getContentPane().setBackground(new Color(14,58,119)); cd.getContentPane().setLayout(null); cd.setResizable(false); ImageIcon backg = new ImageIcon("CDLABEL.PNG"); JLabel cdlogo = new JLabel(backg); cd.getContentPane().add(cdlogo); cdcode = new JLabel("CD Code:"); cdcode.setForeground(Color.white); cdtitle = new JLabel("Title:"); cdtitle.setForeground(Color.white); cdisbn = new JLabel("ISBN NO:"); cdisbn .setForeground(Color.white); cdedit = new JLabel("Edition:"); cdedit .setForeground(Color.white); cdpub = new JLabel("Publication:"); cdpub .setForeground(Color.white); cdcodeTF = new JTextField(); cdtitleTF = new JTextField(); cdisbnTF = new JTextField(); cdeditionTF = new JTextField(); cdpubTF = new JTextField(); cdsearch = new JButton("Search" , new ImageIcon("SEARCH.PNG")); cdsave = new JButton("Save", new ImageIcon("SAVE.PNG")); cddelete = new JButton("Delete", new ImageIcon("DELETE.PNG")); cdupdate = new JButton("Update", new ImageIcon("UPDATE.PNG")); cdexit = new JButton("Exit", new ImageIcon("EXIT.PNG")); cd.getContentPane().add(cdcode); cd.getContentPane().add(cdtitle); cd.getContentPane().add(cdisbn); cd.getContentPane().add(cdedit); cd.getContentPane().add(cdpub); cd.getContentPane().add(cdcodeTF); cd.getContentPane().add(cdtitleTF); cd.getContentPane().add(cdisbnTF); cd.getContentPane().add(cdeditionTF); cd.getContentPane().add(cdpubTF); cd.getContentPane().add(cdsearch); cd.getContentPane().add(cdsave); cd.getContentPane().add(cddelete);

cd.getContentPane().add(cdupdate); cd.getContentPane().add(cdexit); cdlogo.setBounds(1,0,500,100); cdcode.setBounds(50,120,210,25); cdtitle.setBounds(50,160,210,25); cdisbn.setBounds(50,200,210,25); cdedit.setBounds(50,240,210,25); cdpub.setBounds(50,280,210,25); cdcodeTF.setBounds(150,120,210,25); cdtitleTF.setBounds(150,160,210,25); cdisbnTF.setBounds(150,200,210,25); cdeditionTF.setBounds(150,240,210,25); cdpubTF.setBounds(150,280,210,25); cdsearch.setBounds(0,420,98,25); cdsave.setBounds(100,420,98,25); cddelete.setBounds(200,420,98,25); cdupdate.setBounds(300,420,98,25); cdexit.setBounds(400,420,98,25); cdsearch.addActionListener(this); cdsave.addActionListener(this); cddelete.addActionListener(this); cdexit.addActionListener(this); cdupdate.addActionListener(this); cd.setVisible(true); } if(source==cdsearch) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select * from CD where CdCode="+cdcodeTF.getText()); while(rs.next()) { cdtitleTF.setText(rs.getString("Title")); cdisbnTF.setText(rs.getString("IsbnNO")); cdeditionTF.setText(rs.getString("Edition")); cdpubTF.setText(rs.getString("Publication")); } c.close(); st.close(); } catch(ClassNotFoundException cnf) { jp.showMessageDialog(this,cnf,"EXCEPTION",jp.ERROR_MESSAGE); System.out.println("Cnf Exception"); } catch(SQLException sql)

{ jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); }} if(source==cdsave) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps = c.prepareStatement("Insert into CD values(?,?,?,?,?)"); ps.setString(1,cdcodeTF.getText()); ps.setString(2,cdtitleTF.getText()); ps.setString(3,cdisbnTF.getText()); ps.setString(4,cdeditionTF.getText()); ps.setString(5,cdpubTF.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Inserted Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,"Record Already Exists","EXCEPTION",jp.ERROR_MESSAGE); }} if(source==cddelete) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps=c.prepareStatement("Delete from CD where CdCode="+cdcodeTF.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Deleted Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception");

} catch(SQLException sql) { jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); } } if(source==cdupdate) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps=c.prepareStatement ("Update CD set Title=?, IsbnNO=?, Edition=?, Publication=? where CdCode="+cdcodeTF.getText()); ps.setString(1,cdtitleTF.getText()); ps.setString(2,cdisbnTF.getText()); ps.setString(3,cdeditionTF.getText()); ps.setString(4,cdpubTF.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Updated Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); } } if(source==cdexit) { System.exit(0); } if(source==menuItemH) { JFrame help=new JFrame("Help ?"); help.setSize(800,730); help.getContentPane().setBackground(new Color(14,58,119)); help.getContentPane().setLayout(null); help.setResizable(false); ImageIcon hl = new ImageIcon("helpLib.png"); JLabel logoCD = new JLabel(hl); help.getContentPane().add(logoCD); logoCD.setBounds(0,0,800,540);

help.setVisible(true); } if(source==searBook) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select * from Book where BookCode="+bcodeTF.getText()); while(rs.next()) { bookTF.setText(rs.getString("BookName")); authorTF.setText(rs.getString("AuthorName")); priceTF.setText(rs.getString("Price")); /*add.setText(rs.getString("Address")); class1.setText(rs.getString("Class")); progress.setText(rs.getString("Progress")); phno.setText(rs.getString("PhoneNo")); shift.setText(rs.getString("Shift")); city.setText(rs.getString("City")); padd.setText(rs.getString("Permenent_Address")); eadd.setText(rs.getString("eaddress"));*/ } c.close(); st.close(); } catch(ClassNotFoundException cnf) { jp.showMessageDialog(this,cnf,"EXCEPTION",jp.ERROR_MESSAGE); System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); }} if(str1.equals("Search")) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); ResultSet rs = st.executeQuery("select * from Directory where Id="+id.getText()); while(rs.next()) { date.setText(rs.getString("DateToday")); id.setText(rs.getString("Id"));

name.setText(rs.getString("Name")); add.setText(rs.getString("Address")); class1.setText(rs.getString("Class")); progress.setText(rs.getString("Progress")); phno.setText(rs.getString("PhoneNo")); shift.setText(rs.getString("Shift")); city.setText(rs.getString("City")); padd.setText(rs.getString("Permenent_Address")); eadd.setText(rs.getString("eaddress")); } c.close(); st.close(); } catch(ClassNotFoundException cnf) { jp.showMessageDialog(this,cnf,"EXCEPTION",jp.ERROR_MESSAGE); System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); }} if(str1.equals("Save")) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps = c.prepareStatement("Insert into Directory values(?,?,?,?,?,?,?,?,?,?,?)"); ps.setString(1,date.getText()); ps.setString(2,id.getText()); ps.setString(3,name.getText()); ps.setString(4,class1.getText()); ps.setString(5,shift.getText()); ps.setString(6,progress.getText()); ps.setString(7,add.getText()); ps.setString(8,city.getText()); ps.setString(9,padd.getText()); ps.setString(10,phno.getText()); ps.setString(11,eadd.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Inserted Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) {

System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,"Record Already Exists","EXCEPTION",jp.ERROR_MESSAGE); }} if(str1.equals("Delete")) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps=c.prepareStatement("Delete from Directory where Id="+id.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Deleted Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf) { System.out.println("Cnf Exception"); } catch(SQLException sql) { jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); }} if(str1.equals("Update")) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection c = DriverManager.getConnection("jdbc:odbc:Student"); Statement st = c.createStatement(); PreparedStatement ps=c.prepareStatement ("Update Directory set Date=?,Name=?,Class=?,Shift=?,Progress=?,Address=?,City=?,Perm enent_Address=?,PhoneNo=?,eaddress=? where Id="+id.getText()); PreparedStatement ps=c.prepareStatement ("Update Directory set Name=?, Class=?, Shift=?, Progress=?, Address=?, City=?, Permenent_Address=?, PhoneNo=?, eaddress=?, DateToday=? where Id="+id.getText()); ps.setString(1,name.getText()); ps.setString(2,class1.getText()); ps.setString(3,shift.getText()); ps.setString(4,progress.getText()); ps.setString(5,add.getText());

ps.setString(6,city.getText()); ps.setString(7,padd.getText()); ps.setString(8,phno.getText()); ps.setString(9,eadd.getText()); ps.setString(10,date.getText()); ps.executeUpdate(); jp.showMessageDialog(this,"Record Updated Successfully","SUCCESS",jp.INFORMATION_MESSAGE); c.close(); st.close(); } catch(ClassNotFoundException cnf){ System.out.println("Cnf Exception"); } catch(SQLException sql){ jp.showMessageDialog(this,sql,"EXCEPTION",jp.ERROR_MESSAGE); }} if(str1.equals("Exit")){ System.exit(0); }} public static void main(String arg[]){ ProjectLibrary p4 = new ProjectLibrary(); p4.setResizable(false); }}

OUTPUT:

PROGRAM CODING: import java.lang.*; import java.util.*; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; public class TCPChat implements Runnable { public final static int NULL = 0; public final static int DISCONNECTED = 1; public final static int DISCONNECTING = 2; public final static int BEGIN_CONNECT = 3; public final static int CONNECTED = 4; public final static String statusMessages[] = { " Error! Could not connect!", " Disconnected", " Disconnecting...", " Connecting...", " Connected" }; public final static TCPChat tcpObj = new TCPChat(); public final static String END_CHAT_SESSION = new Character((char)0).toString(); // Indicates the end of a session public static String hostIP = "localhost"; public static int port = 1234; public static int connectionStatus = DISCONNECTED; public static boolean isHost = true; public static String statusString = statusMessages[connectionStatus]; public static StringBuffer toAppend = new StringBuffer(""); public static StringBuffer toSend = new StringBuffer(""); public static JFrame mainFrame = null; public static JTextArea chatText = null; public static JTextField chatLine = null; public static JPanel statusBar = null; public static JLabel statusField = null; public static JTextField statusColor = null; public static JTextField ipField = null; public static JTextField portField = null; public static JRadioButton hostOption = null; public static JRadioButton guestOption = null; public static JButton connectButton = null; public static JButton disconnectButton = null; public static ServerSocket hostServer = null; public static Socket socket = null; public static BufferedReader in = null; public static PrintWriter out = null; private static JPanel initOptionsPane() { JPanel pane = null; ActionAdapter buttonListener = null; JPanel optionsPane = new JPanel(new GridLayout(4, 1));

pane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); pane.add(new JLabel("Host IP:")); ipField = new JTextField(10); ipField.setText(hostIP); ipField.setEnabled(false); ipField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { ipField.selectAll(); if (connectionStatus != DISCONNECTED) { changeStatusNTS(NULL, true); } else { hostIP = ipField.getText(); } } }); pane.add(ipField); optionsPane.add(pane); pane = new JPanel(new FlowLayout(FlowLayout.RIGHT)); pane.add(new JLabel("Port:")); portField = new JTextField(10); portField.setEditable(true); portField.setText((new Integer(port)).toString()); portField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { if (connectionStatus != DISCONNECTED) { changeStatusNTS(NULL, true); } else { int temp; try { temp = Integer.parseInt(portField.getText()); port = temp; } catch (NumberFormatException nfe) { portField.setText((new Integer(port)).toString()); mainFrame.repaint(); } } } }); pane.add(portField); optionsPane.add(pane); buttonListener = new ActionAdapter() { public void actionPerformed(ActionEvent e) { if (connectionStatus != DISCONNECTED) { changeStatusNTS(NULL, true); } else { isHost = e.getActionCommand().equals("host"); if (isHost) { ipField.setEnabled(false); ipField.setText("localhost");

hostIP = "localhost"; } else { ipField.setEnabled(true); } } } }; ButtonGroup bg = new ButtonGroup(); hostOption = new JRadioButton("Host", true); hostOption.setMnemonic(KeyEvent.VK_H); hostOption.setActionCommand("host"); hostOption.addActionListener(buttonListener); guestOption = new JRadioButton("Guest", false); guestOption.setMnemonic(KeyEvent.VK_G); guestOption.setActionCommand("guest"); guestOption.addActionListener(buttonListener); bg.add(hostOption); bg.add(guestOption); pane = new JPanel(new GridLayout(1, 2)); pane.add(hostOption); pane.add(guestOption); optionsPane.add(pane); JPanel buttonPane = new JPanel(new GridLayout(1, 2)); buttonListener = new ActionAdapter() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("connect")) { changeStatusNTS(BEGIN_CONNECT, true); } else { changeStatusNTS(DISCONNECTING, true); } } }; connectButton = new JButton("Connect"); connectButton.setMnemonic(KeyEvent.VK_C); connectButton.setActionCommand("connect"); connectButton.addActionListener(buttonListener); connectButton.setEnabled(true); disconnectButton = new JButton("Disconnect"); disconnectButton.setMnemonic(KeyEvent.VK_D); disconnectButton.setActionCommand("disconnect"); disconnectButton.addActionListener(buttonListener); disconnectButton.setEnabled(false); buttonPane.add(connectButton); buttonPane.add(disconnectButton); optionsPane.add(buttonPane); return optionsPane; } private static void initGUI() { statusField = new JLabel();

statusField.setText(statusMessages[DISCONNECTED]); statusColor = new JTextField(1); statusColor.setBackground(Color.red); statusColor.setEditable(false); statusBar = new JPanel(new BorderLayout()); statusBar.add(statusColor, BorderLayout.WEST); statusBar.add(statusField, BorderLayout.CENTER); JPanel optionsPane = initOptionsPane(); JPanel chatPane = new JPanel(new BorderLayout()); chatText = new JTextArea(10, 20); chatText.setLineWrap(true); chatText.setEditable(false); chatText.setForeground(Color.blue); JScrollPane chatTextPane = new JScrollPane(chatText, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); chatLine = new JTextField(); chatLine.setEnabled(false); chatLine.addActionListener(new ActionAdapter() { public void actionPerformed(ActionEvent e) { String s = chatLine.getText(); if (!s.equals("")) { appendToChatBox("OUTGOING: " + s + "\n"); chatLine.selectAll(); sendString(s); } } }); chatPane.add(chatLine, BorderLayout.SOUTH); chatPane.add(chatTextPane, BorderLayout.CENTER); chatPane.setPreferredSize(new Dimension(200, 200)); JPanel mainPane = new JPanel(new BorderLayout()); mainPane.add(statusBar, BorderLayout.SOUTH); mainPane.add(optionsPane, BorderLayout.WEST); mainPane.add(chatPane, BorderLayout.CENTER); mainFrame = new JFrame("Simple TCP Chat"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setContentPane(mainPane); mainFrame.setSize(mainFrame.getPreferredSize()); mainFrame.setLocation(200, 200); mainFrame.pack(); mainFrame.setVisible(true); } private static void changeStatusTS(int newConnectStatus, boolean noError) { if (newConnectStatus != NULL) { connectionStatus = newConnectStatus; } if (noError) { statusString = statusMessages[connectionStatus]; } else {

statusString = statusMessages[NULL]; } SwingUtilities.invokeLater(tcpObj); } private static void changeStatusNTS(int newConnectStatus, boolean noError) { if (newConnectStatus != NULL) { connectionStatus = newConnectStatus; } if (noError) { statusString = statusMessages[connectionStatus]; } else { statusString = statusMessages[NULL]; } tcpObj.run(); } private static void appendToChatBox(String s) { synchronized (toAppend) { toAppend.append(s); } } private static void sendString(String s) { synchronized (toSend) { toSend.append(s + "\n"); } } private static void cleanUp() { try { if (hostServer != null) { hostServer.close(); hostServer = null; } } catch (IOException e) { hostServer = null; } try { if (socket != null) { socket.close(); socket = null; } } catch (IOException e) { socket = null; } try { if (in != null) { in.close(); in = null; } } catch (IOException e) { in = null; } if (out != null) { out.close();

out = null; } } public void run() { switch (connectionStatus) { case DISCONNECTED: connectButton.setEnabled(true); disconnectButton.setEnabled(false); ipField.setEnabled(true); portField.setEnabled(true); hostOption.setEnabled(true); guestOption.setEnabled(true); chatLine.setText(""); chatLine.setEnabled(false); statusColor.setBackground(Color.red); break; case DISCONNECTING: connectButton.setEnabled(false); disconnectButton.setEnabled(false); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(false); statusColor.setBackground(Color.orange); break; case CONNECTED: connectButton.setEnabled(false); disconnectButton.setEnabled(true); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(true); statusColor.setBackground(Color.green); break; case BEGIN_CONNECT: connectButton.setEnabled(false); disconnectButton.setEnabled(false); ipField.setEnabled(false); portField.setEnabled(false); hostOption.setEnabled(false); guestOption.setEnabled(false); chatLine.setEnabled(false); chatLine.grabFocus(); statusColor.setBackground(Color.orange); break; } ipField.setText(hostIP); portField.setText((new Integer(port)).toString()); hostOption.setSelected(isHost);

guestOption.setSelected(!isHost); statusField.setText(statusString); chatText.append(toAppend.toString()); toAppend.setLength(0); mainFrame.repaint(); } public static void main(String args[]) { String s; initGUI(); while (true) { try { // Poll every ~10 ms Thread.sleep(10); } catch (InterruptedException e) {} switch (connectionStatus) { case BEGIN_CONNECT: try { if (isHost) { hostServer = new ServerSocket(port); socket = hostServer.accept(); } else { socket = new Socket(hostIP, port); } in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); changeStatusTS(CONNECTED, true); } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case CONNECTED: try { if (toSend.length() != 0) { out.print(toSend); out.flush(); toSend.setLength(0); changeStatusTS(NULL, true); } if (in.ready()) { s = in.readLine(); if ((s != null) && (s.length() != 0)) { if (s.equals(END_CHAT_SESSION)) { changeStatusTS(DISCONNECTING, true); } else { appendToChatBox("INCOMING: " + s + "\n"); changeStatusTS(NULL, true);

} } } } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case DISCONNECTING: out.print(END_CHAT_SESSION); out.flush(); cleanUp(); changeStatusTS(DISCONNECTED, true); break; default: break; // do nothing } } } } class ActionAdapter implements ActionListener { public void actionPerformed(ActionEvent e) {} }

OUTPUT:

You might also like