Sunteți pe pagina 1din 96

JAVA LAB

Ex.No:1 Date:

RATIONAL NUMBER CLASS IN JAVA

Aim: To write a program in Java with the following: (i) (ii) Develop a Rational number class. Use JavaDoc comments for documentation i.e. (500/1000) should be represented as (1/2). Algorithm: 1. Start the program. 2. Declare a class called Rational and invoke a function called gcd(a,b). 3. Find out the reminder when a is divided by b and pass it as a parameter to the function. 4. Create an object for the class and declare the required string and integer variables. 5. Create an object of class DataInputStream .Read thenumbers through the ReadLine() method into the object. 6. Convert the input accepted into Integers through the parseInt method and store them in variables a and b. 7. Store the value returned by the function GCD in variable 8. Divide a by l and b by l and store them in variables x and y. 9. Stop the Program. Program: import java.util.*; public class RationalClass { private int numerator; private int denominator; public RationalClass(int numerator,int denominator) { if(denominator==0) { throw new RuntimeException("Denominator is zero"); } int g=gcd(numerator,denominator);
2

(iii) Implementation should use efficient representation for a rational number,

if(g==1) { System.out.println("No Common Divisor for Numerator and Denominator"); this.numerator=numerator; this.denominator=denominator; } else { this.numerator=numerator/g; this.denominator=denominator/g; } } public String display() { return numerator+"/"+denominator; } private static int gcd(int n,int d) { if(d==0) return n; else return gcd(d,n%d); } public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter Numerator : "); int numerator=input.nextInt(); System.out.print("Enter Denominator : "); int denominator=input.nextInt(); RationalClass rational = new RationalClass(numerator,denominator); String str=rational.display(); System.out.println("Efficient Representation for the rational number :" +str); } }

Output:

SUPPLEMENTARY PROGRAMS: 1. Develop the Java program to reverse String in Java without using API functions? 2. Develop the Java program to print Fibonacci series upto 100? 3. Develop the Java program to Java program to find if a number is prime number or not? 4. Develop the Java program to check if a number is Armstrong or not (Eg. 371 is Armstrong Number [33+73 +13 = 371])? 5. Develop the Java program to print following structure in Java * *** ***** *** * If the user input data in 5.

Viva Questions: 1. Define Package ? 2. What are the main application of Package ? 3. Code to get the user input dynamically? 4. What is CommandLine Arguments ? 5. Explain the features of Java Language ?
4

Result: Thus the above program was executed and verified successfully.

Ex.No:2 Date:

DATE CLASS IN JAVA

Aim: To develop Date class in Java similar to the one available in java.util package. Use JavaDoc comments for documentation. Algorithm: 1. Start the program. 2. Declare a class called Date example and create an object called date. 3. Display the Date and Time through these objects with the Methods in Date Class. 4. Declare two objects called start time and end time for this class. 5. Create another object called changed object and display the changed time with the calculation 24L*60L*60L*1000L. 6. In the main function create object for the class Date and display the time and date accordingly. 7. Stop the program. Program: import java.text.*; import java.util.*; /** *Class DateFormatDemo formats the date and time by using java.text package */ public class DateFormatDemo { public static void main(String args[]) { /** * @see java.util package */ Date date=new Date();
5

/** * @see java.text package */ DateFormat df; System.out.println("Current Date and Time - Available in java.util Package:"); System.out.println("-------------------------------------------------------"); System.out.println(date); System.out.println(); System.out.println("Formatted Date - Using DateFormat Class from java.text Package:"); System.out.println("---------------------------------------------------------------"); df=DateFormat.getDateInstance(DateFormat.DEFAULT); System.out.println("Default Date Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.SHORT); System.out.println("Date In Short Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.MEDIUM); System.out.println("Date In Medium Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.LONG); System.out.println("Date In Long Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.FULL); System.out.println("Date In Full Format:"+df.format(date)); System.out.println(); System.out.println("Formatted Time - Using DateFormat Class from java.text Package:"); System.out.println("---------------------------------------------------------------"); df=DateFormat.getTimeInstance(DateFormat.DEFAULT); System.out.println("Default Time Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.SHORT); System.out.println("Time In Short Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.MEDIUM); System.out.println("Time In Medium Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.LONG); System.out.println("Time In Long Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.FULL); System.out.println("Time In Full Format:"+df.format(date)); System.out.println();
6

System.out.println("Formatted Date and Time - Using SimpleDateFormat Class from java.text Package:"); System.out.println("------------------------------------------------------------------------------"); /** * @see java.text package */ SimpleDateFormat sdf; sdf=new SimpleDateFormat("dd MMM yyyy hh:mm:sss:S E w D zzz"); System.out.println(sdf.format(date)); } }

Output:

Supplementary Programs: 1. Develop Calendar class in Java similar to the one available in java.util package 2. Develop timezone class in Java similar to the one available in java.util package 3. Develop Random class in Java similar to the one available in java.util package Viva Questions: 1. What is the use of JavaDoc comments ?
8

2. Define some other methods under object java.text? 3. Define some other methods under object java.util ? 4. What is syntax for getDateInstance() function and its application ? 5. What is the main purpose of using java.text object ?

Result: Thus the above program was executed and verified successfully.

Ex.No:3 Date:

LISP-LIKE LIST IN JAVA

Aim: To implement Lisp-like list in Java that performs the basic operations such as 'car', 'cdr', and 'cons'. Algorithm: 1. Start the program. 2. Create a node of a list having data part and link part. 3. Create a menu having the following choices : insert, car, cdr, adjoin and display. 4. Read the choice from the user and call the respective methods. 5. Create another class which implements the same interface to implement the concept of stack through linked list. 6. Car class will return the first node data. 7. CDR will return the entire node (data part) in the list except the first node. 8. Stop the program. Program: import java.util.*; class Lisp
9

{ public Vector car(Vector v) { Vector elt=new Vector(); elt.addElement(v.elementAt(0)); return elt; } public Vector cdr(Vector v) { Vector elt=new Vector(); for(int i=1;i<v.size();i++) elt.addElement(v.elementAt(i)); Output:

Supplementary Program: 1. Write a java program to implement the Lisp-like list by defining two vectors and perform the
addition operation for the defined vector.

2. Write a java program to implement the Lisp-like list by defining a vector and perform the
sum of all elements in the defined vector.

Viva Questions:
10

1. Define Lisp list? 2. What are the available operations in Lisp list? 3. What is the function to check whether the object is empty or not?

Result: Thus the above program was executed and verified successfully. return elt; } public Vector cons(int x, Vector v) { v.insertElementAt(x,0); return v; } } class LispOperation { public static void main(String[] args) { Lisp L=new Lisp(); Vector v=new Vector(4,1); v.addElement(3); v.addElement(0); v.addElement(2); v.addElement(5); System.out.println("Basic Lisp Operations"); System.out.println("---------------------"); System.out.println("The Elements of the List are:"+v); System.out.println("Lisp Operation-CAR:"+L.car(v));
11

System.out.println("Lisp Operation-CDR:"+L.cdr(v)); System.out.println("Elements of the List After CONS:"+L.cons(9,v)); } }

12

13

14

Ex.No:4 Date:

JAVA INTERFACE FOR ADT STACK

Aim: To Design a Java interface for ADT Stack with the following: (i) Develop a class that implement this interface. (ii)Provide necessary exception handling in the implementation. Algorithm: 1. 2. 3. 4. 5. 6. 7. 8. 9. Start the program. Create an interface which consists of three methods namely PUSH, POP and DISPLAY Create a class which implements the above interface to implement the concept of stack through Array Define all the methods of the interface to push any element, to pop the top element and to display the elements present in the stack. Create another class which implements the same interface to implement the concept of stack through linked list. Repeat STEP 5 for the above said class also. In the main class, get the choice from the user to choose whether array implementation or linked list implementation of the stack. Call the methods appropriately according to the choices made by the user in the previous step. Repeat step 7 and step 8 until the user stops his/her execution 10. Stop the Program
15

Program: import java.io.*; import java.util.*; interface stackInterface { int n=50; public void pop();

16

public void push(); public void display(); } class stack implements stackInterface { int arr[]=new int[n]; int top=-1; Scanner in=new Scanner(System.in); public void push() { try { System.out.println("Enter The Element of Stack"); int elt=in.nextInt(); arr[++top]=elt; } catch (Exception e) { System.out.println("e"); } } public void pop() { int pop=arr[top]; top--; System.out.println("Popped Element Is:"+pop);
17

} public void display() { if(top<0) { System.out.println("Stack Is Empty"); return; } Output:

18

else {
19

String str=" "; for(int i=0;i<=top;i++) str=str+" "+arr[i]; System.out.println("Stack Elements Are:"+str); } } } class StackADT { public static void main(String arg[])throws IOException { System.out.println("JAVA INTERFACE FOR STACK ADT"); System.out.println("============================"); Scanner in=new Scanner(System.in); stack st=new stack(); int no=0; do { System.out.println("1.push \n2.pop \n3.display \n4.Exit"); System.out.println(); System.out.print("Enter Your Choice:"); no=in.nextInt(); switch(no) { case 1: st.push(); break; case 2: st.pop(); break; case 3: st.display(); Supplementary Program:
20

1. Design a Java interface for ADT Queue . 2. Design a Java interface for ADT Linked List. Viva Questions: 1. Define stack and the operations performed in stack? 2. Define queue and the operations performed in stack? 3. Define linked list and the operations performed in stack? 4. Define interface? What are the advantages of using interfaces in program? 5. How will you initialize arrays?

Result: Thus the above program was executed and verified successfully.

21

break; case 4: System.exit(0); } } while(no<=5); } }

22

23

24

25

26

Ex.No:5 Date:

VEHICLE CLASS HIERARCHY IN JAVA

Aim: To design a vehicle class hierarchy in Java that demonstrates the concept of polymorphism. Algorithm: 1. Start the program. 2. Create an abstract class named vehicle with abstract method Display and a concrete method Input. 3. Define the input method by prompting the user to enter the values for name, owner, type, number, engine capacity, seating capacity for the vehicle; all the inputs taken in the form string. 4. Extend three classes namely twowheeler , threewheeler , fourwheeler from the base class. 5. Define the method display under the class VehicleDemo by displaying all the entered values. 6. Repeat step 5 for the class VehicleDemo.
27

7. Extend the input method for the class Vehicle by taking in the value of wheeling capacity for the vehicle in the form of string. 8. In the main method create a reference for the abstract class and create a switch case to perform operations on the opted class. 9. Under each class create a switch case to either enter the data or to display the transport report. 10. Repeat the main menu on the user's choice. 11. Create array of objects under each class and call the methods by assigning the values of the created objects to the reference object, to show polymorphism. 12. Stop the program.

28

Program: import java.io.*; class Vehicle { String regno; int model; Vehicle(String r, int m) { regno=r; model=m; } void display() { System.out.println("Registration Number:"+regno); System.out.println("Model Number:"+model); } } class Twowheeler extends Vehicle {
29

int wheel; Twowheeler(String r,int m,int n) { super(r,m); wheel=n; } void display() { System.out.println("Vehicle : Two Wheeler"); System.out.println("====================="); super.display(); System.out.println("Number of Wheels:"+wheel+"\n"); } } class Threewheeler extends Vehicle

30

{ int leaf; Threewheeler(String r,int m,int n) { super(r,m); leaf=n; } void display() { System.out.println("Vehicle : Three Wheeler"); System.out.println("======================="); super.display(); System.out.println("Number of Leaf:"+leaf+"\n"); } } class Fourwheeler extends Vehicle { int leaf; Fourwheeler(String r,int m,int n)
31

{ super(r,m); leaf=n; } void display() { System.out.println("Vehicle : Four Wheeler"); System.out.println("======================"); super.display(); System.out.println("Number of Leaf:"+leaf); } } public class VehicleDemo { public static void main(String arg[]) Output:

Supplementary Programs: 1. Write a Java Program implementing class hierarchy with person as base class and employee, student, customer as derived class. 2. Write a java program implementing Multilevel Inheritance (eg. Higher Education
32

Arts

Engg.

B.Sc VIVA QUESTIONS:

BCA

BE CSE E

BE ECE

1. Define Inheritance? 2. What are the types of inheritance? 3. How is multiple inheritances achieved in java? 4. What is Inheritance Hierarchy? 5. What is the use of super keyword? Result: Thus the above program was executed and verified successfully. { Twowheeler two=new Twowheeler("TN75 9843", 2011,2); Threewheeler three=new Threewheeler("TN30 8766", 2010,3); Fourwheeler four=new Fourwheeler("TN15 2630",2009,4); two.display(); three.display(); four.display(); } }

33

34

35

36

Ex.No:6 Date:

OBJECT SERIALIZATION

Aim: To write a program in java to demonstrate object serialization with the following: (i) Design classes for Currency, Rupee, and Dollar. (ii) Write a program that randomly generates Rupee and Dollar objects and write them into a file using object serialization. (iii) Write another program to read that file. (iv) Convert to Rupee if it reads a Dollar and leave the value if it reads a Rupee. Algorithm For writeobj.java : 1. Start the program. 2. Create a class named currency that implements the serializable interface and also it is the base class for rupee and dollar classes. 3. Create an object for ObjectOutputStream to open a file in write mode using FileOutputStream. 4. Read the user choice to enter rupee or dollar amount.
37

5. Generate random numbers as the value of rupee or dollar. 6. If choice is rupee then, append "Rs" to the value generated, else if choice is dollar append "$" to the value generated. 7. Display the appended String and also write it into the file opened using the writeObject() method. 8. Stop the program Algorithm For readobj.java: 1. Start the program. 2. Create a class named currency that implements the serializable interface and also it is the base class for rupee and dollar classes. 3. Create an object for ObjectInputStream to open the file created in program1 in read mode using FileInputStream. 4. If the file does not exist or if it is empty show exceptions. 5. While the End of file is not reached, do the following... (i) If the value read is a dollar convert into rupee and print to the user otherwise print the rupee as such. 6. End the program.

38

Program: writeObj.java import java.io.*; import java.util.*; abstract class Currency implements Serializable { protected double money; public abstract double getValue(); public abstract String printObj(); public Currency(double money) { this.money=money; } } class Dollar extends Currency { public Dollar(int money)
39

{ super(money); } public double getValue() { return this.money*51; } public String printObj() { String object="Object Name : Dollar\nUSD : $"+this.money+"\nINR : Rs"+getValue()+"\n"; return object; } } class Rupee extends Currency { public Rupee(int amount) { Output:

40

super(amount); }
41

public double getValue() { return this.money; } public String printObj() { String object="Object Name : Rupee \nINR : Rs "+getValue()+"\n"; return object; } } public class writeObj { public static void main(String[] args) throws FileNotFoundException,IOException { FileOutputStream fos=new FileOutputStream("currencyInfo.txt"); ObjectOutputStream oos=new ObjectOutputStream(fos); Random rand=new Random(); for(int i=0;i<10;i++) { Object[] obj={new Rupee(rand.nextInt(100)),new Dollar(rand.nextInt(100))}; Currency currency=(Currency)obj[rand.nextInt(2)]; oos.writeObject(currency); } oos.writeObject(null); oos.close(); } }

Supplementary Program:
42

1. Write a program in java to demonstrate object serialization with the following a. Create Gold Price list dynamically and write them into a file using object serialization.
b. Write another program to read that file.

2. Write a program in java to demonstrate object serialization with the following a. Create a Company share list dynamically and write them into a file using object serialization.
b. Write another program to read that file.

Viva Questions: 1. What is Serialization? 2. What is the need of Serialization? 3. Other than Serialization what are the different approach to make object Serializable? 4. What happens if the object to be serialized includes the references to other serializable objects and to other non-serializable objects? 5. If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from super class after deserialization? 6. Does the order in which the value of the transient variables and the state of the object using the defaultWriteObject() method are saved during serialization matter? 7. How can one customize the Serialization process? or What is the purpose of implementing the writeObject() and readObject() method?

Result: Thus the above program was executed and verified successfully.

43

readObj.java import java.io.*; public class readObj { public static void main(String[] args) throws IOException,ClassNotFoundException { Currency currency=null; FileInputStream fis=new FileInputStream("currencyInfo.txt"); ObjectInputStream ois=new ObjectInputStream(fis); while((currency=(Currency)ois.readObject())!=null) { System.out.println(currency.printObj()); } ois.close(); } }

44

45

46

Ex.No:7 Date:

SCIENTIFIC CALCULATOR IN JAVA


47

Aim: To design a scientific calculator using event-driven programming paradigm of Java. ALGORITHM: 1. Start the program. 2. Create a panel consisting of Buttons for various scientific operations. 3. Create Button actions. 4. Place the panel onto a frame. 5. Associate each Button click with the corresponding actionlistener. 6. Stop the program. Program: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.*; public class SimpleCalculator { public static void main(String[] args) { CalcFrame cf=new CalcFrame(); cf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cf.setVisible(true); } } class CalcFrame extends JFrame { public CalcFrame() { setTitle("CALCULATOR"); CalcPanel panel=new CalcPanel();

48

add(panel); pack(); } }
49

class CalcPanel extends JPanel { JButton display; JPanel panel; double result; String lastcmd; boolean start; public CalcPanel() { setLayout(new BorderLayout()); result=0; lastcmd="="; start=true; display=new JButton("0"); display.setEnabled(false); add(display,BorderLayout.NORTH); ActionListener insert=new InsertAction(); ActionListener cmd=new CommandAction(); panel=new JPanel(); panel.setLayout(new GridLayout(5,4)); addButton("1",insert); addButton("2",insert); addButton("3",insert); addButton("/",cmd); addButton("4",insert); addButton("5",insert); addButton("6",insert); addButton("*",cmd); addButton("7",insert); addButton("8",insert);

50

addButton("9",insert); addButton("-",cmd); addButton("0",insert); addButton(".",insert);


51

addButton("pow",cmd); addButton("+",cmd); addButton("sin",insert); addButton("cos",insert); addButton("tan",insert); addButton("=",cmd); add(panel, BorderLayout.CENTER); } private void addButton(String label,ActionListener listener) { JButton button=new JButton(label); button.addActionListener(listener); panel.add(button); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String input=ae.getActionCommand(); if(start==true) { display.setText(""); start=false; } if(input.equals("sin")) { Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.sin(angle)); } else if(input.equals("cos"))

52

{ Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.cos(angle)); }


53

else if(input.equals("tan")) { Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.tan(angle)); } else display.setText(display.getText()+input); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String command=ae.getActionCommand(); if(start==true) { if(command.equals("-")) { display.setText(command); start=false; } else lastcmd=command; } else { calc(Double.parseDouble(display.getText())); lastcmd=command; start=true; } Output:

54

Supplementary Programs: 1. Design an Editor (like Notepad) using Java.


2. Design a simple paint-like program that can draw basic graphical primitives in different dimensions and colors. Use appropriate menu and buttons.

Viva Questions: 1. What is Event-Driven-Thread (EDT) in Swing? 2. What is the purpose of "java.awt" package. Specify usage and some functions available in "java.awt" package? 3. What is the purpose of "java.awt.event" package. Specify usage and some functions available in "java.awt.event" package? 4. Does Swing is thread safe? What do you mean by swing is not thread-safe? 5. What are differences between Swing and AWT? 6. Why Swing components are called lightweight component? 7. What is difference between invokeAndWait and invokeLater?

Result:
55

Thus the above program was executed and verified successfully. } } public void calc(double x) { if(lastcmd.equals("+")) result=result+x; else if(lastcmd.equals("-")) result=result-x; else if(lastcmd.equals("*")) result=result*x; else if(lastcmd.equals("/")) result=result/x; else if(lastcmd.equals("=")) result=x; else if(lastcmd.equals("pow")) { double powval=1.0; for(double i=0.0;i<x;i++) powval=powval*result; result=powval; } display.setText(""+ result); } }

56

57

58

Ex.No:8 Date:

MULTITHREADING IN JAVA

59

Aim: To write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both. Algorithm: 1. Start the program. 2. Design a thread that generates prime numbers below 100,000 and writes them into a pipe. 3. Design another thread that generates fibonacci numbers and writes them to another pipe. 4. Design a main thread should read both the pipes to identify numbers common to both prime and Fibonacci and print all the numbers common to both prime and Fibonacci. 5. Stop the program. Program: import java.util.*; import java.io.*; class Fibonacci extends Thread { private PipedWriter out=new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() {

60

Thread t=Thread.currentThread(); t.setName("Fibonacci"); System.out.println(t.getName()+" Thread started...");


61

int fibo=0,fibo1=0,fibo2=1; while(true) { try { fibo=fibo1+fibo2; if(fibo>100000) { out.close(); break; } out.write(fibo); sleep(1000); } catch(Exception e) { System.out.println("Exception:"+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; }

62

public void run() { Thread t=Thread.currentThread();


63

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) Output:

64

Supplementary Programs: 1. Write a multi-threaded Java program implementing the watch mechanism. Create Thread for
seconds, minutes, hours, date, day, month and display the details correspondingly.

2. Write a java program to print the alphabets between sequence of numbers using multithreading concepts. Viva Questions: 1. Define Thread? What are the advantages of using Threads? 2. What are the methods available in Thread and explain its purpose? 3. Difference between thread and process? 4. What is context switching in multi-threading? 5. Difference between deadlock and livelock, deadlock and starvation? 6. What thread-scheduling algorithm is used in Java? 7. How do you handle un-handled exception in thread?

Result: Thus the above program was executed and verified successfully.

65

return false; return true; } } public class MultiThreadDemo { public static void main(String[] args)throws Exception { Thread t=Thread.currentThread(); t.setName("Main"); System.out.println(t.getName()+" Thread Started..."); Fibonacci fibObj=new Fibonacci(); Prime primeObj=new Prime(); PipedReader pr=new PipedReader(fibObj.getPipedWriter()); PipedReader pr1=new PipedReader(primeObj.getPipedWriter()); fibObj.start(); primeObj.start(); int fib=pr.read(),prm=pr1.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=pr1.read(); } fib=pr.read(); } System.out.println(t.getName()+ " Thread exiting..."); } }

66

67

68

69

Ex.No:9 Date:

OPAC SYSTEM USING JAVA

Aim: To develop a simple OPAC system for library using event-driven programming paradigms of Java.Use JDBC to connect to a back-end database. Algorithm: 1. Start the program. 2. Create a Master Database1 (Book Details) having the following fields: BookNo. , Book Name, Author, No. of pages, Name of Publisher, Cost. 3. Create a Master Database2(User Details) having the following fields : UserID, Department 4. Create a Transaction Database having the following fields: UserID,Book No., Date of Renewal / Date of Return, Fine 5. Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button actions with listeners(with Master Database 1) 6. Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button actions with listeners(with Master Database 2) 7. Create another panel consisting of buttons UserID, BookID, Return/Renewal, Fine. 8. Associate these buttons with listeners (with Transaction Database). 9. Stop the program. Program: import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class OpacSystem implements ActionListener { JRadioButton author=new JRadioButton("Search By Author"); JRadioButton book=new JRadioButton("Search by Book"); JTextField txt=new JTextField(30); JLabel label=new JLabel("Enter Search Key");
70

71

JButton search=new JButton("SEARCH"); JFrame frame=new JFrame(); JTable table; DefaultTableModel model; String query="select*from opacTab"; public OpacSystem() { frame.setTitle("OPAC SYSTEM"); frame.setSize(800,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); JPanel p1=new JPanel(); p1.setLayout(new FlowLayout()); p1.add(label); p1.add(txt); ButtonGroup bg=new ButtonGroup(); bg.add(author); bg.add(book); JPanel p2=new JPanel(); p2.setLayout(new FlowLayout()); p2.add(author); p2.add(book); p2.add(search); search.addActionListener(this); JPanel p3=new JPanel(); p3.setLayout(new BorderLayout()); p3.add(p1,BorderLayout.NORTH); p3.add(p2,BorderLayout.CENTER); frame.add(p3,BorderLayout.NORTH); addTable(query); frame.setVisible(true); } public void addTable(String str) {
72

73

try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:opacDS"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(str); ResultSetMetaData rsmd=rs.getMetaData(); int cols=rsmd.getColumnCount(); model=new DefaultTableModel(1,cols); table=new JTable(model); String[] tabledata=new String[cols]; int i=0; while(i<cols) { tabledata[i]=rsmd.getColumnName(i+1); i++; } model.addRow(tabledata); while(rs.next()) { for(i=0;i<cols;i++) tabledata[i]=rs.getObject(i+1).toString(); model.addRow(tabledata); } frame.add(table,BorderLayout.CENTER); con.close(); } catch(Exception e) { System.out.println("Exception:"+e); } } public void actionPerformed(ActionEvent ae) {
74

Output:

Supplementary Program: 1. Using JDBC create the even-driven programming for student mark entry. 2. Using JDBC create the even-driven programming to create, view and alter employee profile. Viva Questions: 1. What is JDBC? 2. What are the main steps in java to make JDBC connectivity? 3. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? 4. Explain the JDBC Architecture? 5. What are the main components of JDBC? 6. Code to call the query / stored procedure from JDBC?
75

7. Code to set the JDBC Connection with the Database server?

Result: Thus the above program was executed and verified successfully. if(author.isSelected()) query="select*from opacTab where AUTHOR like '"+txt.getText()+"%'"; if(book.isSelected()) query="select*from opacTab where BOOK like '"+txt.getText()+"%'"; while(model.getRowCount()>0) model.removeRow(0); frame.remove(table); addTable(query); } public static void main(String[] args) { OpacSystem os=new OpacSystem(); } }

76

77

78

79

Ex.No:10 Date:

MULTI-THREADED ECHO SERVER

Aim: To develop a multi-threaded echo server and a corresponding GUI client in Java. Algorithm for Server: 1. Start the program. 2. Establish the connection of socket. 3. Assign the local Protocol address to the socket. 4. Move the socket from closed to listener state and provide maximum no. of Connections. 5. Create a new socket connection using client address. 6. Read the data from the socket. 7. Write the data into socket. 8. Close the socket. 9. Stop the program. Program: EchoServer.java import java.io.*; import java.net.*; public class EchoServer { public static void main(String [] args) { System.out.println("Server Started...."); try { ServerSocket ss=new ServerSocket(300); while(true) { Socket s= ss.accept(); Thread t = new ThreadedServer(s); t.start();
80

81

} } catch(Exception e) { System.out.println("Error: " + e); } } } class ThreadedServer extends Thread { Socket soc; public ThreadedServer(Socket soc) { this.soc=soc; } public void run() { try { BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out=new PrintWriter(soc.getOutputStream()); String str=in.readLine(); System.out.println("Message From Client:"+str); out.flush(); out.println("Message To Client:"+str); out.flush(); } catch(Exception e) { System.out.println("Exception:"+e); } } }

82

Output: Server:

Client:

EchoClient.java
83

import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; class EchoClient extends JFrame { JTextArea ta; JTextField msg; JPanel panel; JScrollPane scroll; JButton b1=new JButton("Close"); JButton b2=new JButton("Send"); JLabel l1=new JLabel("Echo Client GUI"); Container c; EchoClient() { c=getContentPane(); setSize(300,470); setTitle("GUI Client"); panel=new JPanel(); msg=new JTextField(20); panel.setLayout(new FlowLayout(FlowLayout.CENTER)); ta=new JTextArea(20,20); scroll=new JScrollPane(ta); panel.add(l1); panel.add(ta); panel.add(msg); panel.add(b2); panel.add(b1); c.add(panel); b2.addActionListener(new ActionListener() {

84

Supplementary Program: 1. Develop the Multiuser chat application using java 2. Develop the echo server and a corresponding GUI client for transferring the files.

Viva Questions: 1. Define Socket? What is the purpose of using Socket? 2. Name the seven layers of the OSI Model and describe them briefly? 3. What are some advantages and disadvantages of Java Sockets? 4. What are the functions available in "java.net" package? 5. What is the functionality of "flush" function? 6. Define Exception handling? Why we ned to use Exception handling in our code? Syntax for try catch exception? 7. What are the functions available in "java.awt.event" package? 8. What is the function used to send the message to server / other client?

Result:
85

Thus the above program was executed and verified successfully. public void actionPerformed(ActionEvent ae) { try { Socket s=new Socket("localhost",300); BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); out.println(msg.getText()); out.flush(); String temp =ta.getText(); if(temp.equalsIgnoreCase("quit")) { System.exit(0); } msg.setText(""); ta.append("\n"+in.readLine()); } catch (IOException e) { ta.setText("Exception:"+e); } } { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); { EchoClient frame=new EchoClient(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
86

} );

b1.addActionListener(new ActionListener()

public static void main(String args[])

87

88

Additional Viva Questions: 1. What are the OOP Principles? 2. What is Encapsulation? 3. What is Polymorphism? 4. What is Inheritance? 5. What are the features of Java Language? 6. What is the need for Java Language? 7. What is platform independency? 8. What is Architecture Neutral? 9. How Java supports platform independency? 10. Why Java is important to Internet? 11. What are the types of programs Java can handle? 12. What is an applet program? 13. Compare Application and Applet. 14. What are the advantages of Java Language? 15. Give the contents of Java Environment (JDK). 16. Give any 4 differences between C and Java. 17. Give any 4 differences between C++ and Java. 18. What are the different types of comment symbols in Java? 19. What are the data types supported in Java? 20. What is the difference between a char in C/C++ and char in Java? 21. How is a constant defined in Java? 22. What is the use of final keyword?
89

23. What are the different types of operators used in Java? 24. What is short-Circuit operator? 25. What is labeled break? 26. What is the use of for each control structure? 27. What is the need for static variables? 28. What is the need for static methods? 29. Compare static constants and final constants. 30. Why is main method assigned as public? 31. Why is main method assigned as static? 32. What are the types of variables Java handles? 33. What are the relationships between classes? 34. What is the general form of a class? 35. What is the use of new keyword? 36. If ObjA1 is an object of class A created using new keyword, What does the statement A ObjA2=ObjA1; mean?

37. What is a constructor? 38. What is the difference between a constructor and a method? 39. What is the use of this keyword? 40. What are destructors? 41. How is object destruction done in Java? 42. What is Garbage collection? 43. What is the use of finalize method? 44. Compare Garbage collection and finalize method? 45. How is it guaranteed that finalize methods are called?
90

46. What is method overloading? 47. What is a String in Java? 48. What is the difference between a String in Java and String in C/C++? 49. Name a few String methods. 50. What is the difference between Concat method and + operator to join strings? 51. What is String Buffer? 52. How does String class differ from the String Buffer class? 53. Name some methods available under String Buffer class. 54. Output of some expressions using String methods. 55. How will you initialize arrays? 56. What is arraycopy method? Explain with syntax. 57. What are the methods under Util.Arrays? 58. Use the array sort method to sort the given array. 59. Give the syntax for array fill operation. 60. What is vector? How is it different from an array? 61. What is the constraint for using vectors? 62. What is wrapper class? 63. What are the different access specifiers available in Java? 64. What is the default access specifier in Java? 65. What is a package in Java? 66. Name some Java API Packages. 67. Name some JavaDoc Comments. 68. What is CommandLine Arguments.
91

69. Explain OOP Principles. 70. Explain the features of Java Language. 71. Compare and Contrast Java with C. 72. Compare and Contrast Java with C++. 73. Explain Constructors with examples. 74. Explain the methods available under String and String Buffer Class. 75. Explain the Date Class methods with examples. 76. Discuss in detail the access specifiers available in Java. 77. Explain the different visibility controls and also compare with each of them. 78. Explain the different methods in java.Util.Arrays class with example. 79. Explain Packages in detail. 80. Discuss the methods under Array Class. 81. Discuss some of the classes available under Lang package. 82. Illustrate with examples: static and final. 83. Explain method overriding with example program. 84. What is javaDoc? Explain the comments for classes, methods, fields and link. 85. Application Programs in Java. 86. Define Inheritance 87. What are the types of inheritance? 88. How is multiple inheritance achieved in java? 89. What is the use of super keyword? 90. What are object wrappers? Give example. 91. What is Inheritance Hierarchy?
92

92. Differentiate overloading and overriding. 93. Define polymorphism. 94. Differentiate static binding and dynamic binding. 95. When will a class be declared as final? 96. When will a method be declared final? 97. What is an abstract class? 98. What is the need for abstract classes? 99. Explain about protected visibility control. 100. What are the methods under "object" class / java.lang.Object. 101. 102. 103. 104. 105. classes? 106. 107. 108. 109. 110. 111. 112. 113. 114. How to create arrays dynamically using reflection package. Define an interface. What is the need for an interface? What are the properties of an interface? Differentiate Abstract classes and interface. What is object cloning? Differentiate cloning and copying. Differentiate shallow copy and deep copy in cloning. Does Inheritance removes any fields/or methods of super class?
93

Explain toString method of object class. What is reflection? What are the uses of reflection in Java. How will you create an instance of Class. What are the methods under reflection used to analyze the capabilities of

115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. Swing. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137.

Mention the use of final keyword. What is nested class? Mention its types. What is inner class? What is the need for inner classes? What are the rules for inner class? What is local inner class and anonymous inner class? Give their advantages. Write the advantages and disadvantages of static nested class. Define proxies. Write the application of proxies. What are the properties of proxy classes? Draw the inheritance hierarchy for the frame and component classes in AWT and

What are the advantages of using swing over awt? How do achieve special fonts for your text? Give example. Give the syntax of drawImage() and copyArea() methods. What is Adapter class? Draw the AWT event Hierarchy. What are the swing components? What are the methods under Action Interface. What are the methods under WindowListener Interface. What is the difference between Swing and AWT? What is generic programming? What are Checked and UnChecked Exception? What are checked exceptions?
94

138. 139. 140. 141.

What are runtime exceptions? What is the difference between error and an exception? What classes of exceptions may be caught by a catch clause?. If I want an object of my class to be thrown as an exception object, what should I do?

142. 143. 144. 145.

How to create custom exceptions? What are the different ways to handle exceptions? What is the purpose of the finally clause of a try-catch-finally statement? What is the basic difference between the 2 approaches to exception handling. Is it necessary that each try block must be followed by a catch block?

146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159.

How does Java handle integer overflows and underflows? Explain generic classes and methods. Explain exception hierarchy. What are the advantages of Generic Programming? Explain the different ways to handle exceptions. How Java handle overflows and underflows? Describe synchronization in respect to multithreading. Explain different way of using thread? What is synchronization and why is it important? When a thread is created and started, what is its initial state? What are synchronized methods and synchronized statements? What is daemon thread and which method is used to create the daemon thread? What method must be implemented by all threads? What kind of thread is the Garbage collector thread?
95

160. 161. 162. 163. 164. 165. 166. 167. 168. 169.

What is a daemon thread? What is a thread? What is the algorithm used in Thread scheduling? What are the different level lockings using the synchronization keyword? What are the ways in which you can instantiate a thread? What are the states of a thread? What are the threads will start, when you start the java program? What are the different identifier states of a Thread? Why do threads block on I/O? What is synchronization and why is it important?

96

S-ar putea să vă placă și