Certified that this the bonafide record of work done by the student in the
Laboratory.
STAFF-IN CHARGE HOD
Submitted for the Practical Examination held on
INTERNAL EXAMINER EXTERNAL EXAMINER
BONAFIDE CERTIFICATE 2
TABLE OF CONTENTS
S.NO DATE EXPERIMENTS PAGE STAFF NO SIGN
1. RATIONAL NUMBER
2. DATE CLASS IN JAVA
3. IMPLEMENT LISP-LIKE LIST IN JAVA
4. JAVA INTERFACE FOR STACK ADT USING ARRAY AND LINKED LIST
5. VEHICLE CLASS HIERARCHY (POLYMORPHISM)
6. OBJECT SERIALISATION
7. SCIENTIFIC CALCULATOR
8. MULTITHREADED JAVA PROGRAM FIBONACCI NUMBER,PRIME NUMBER BELOW 100000 AND WRITE THEM INTO A PIPE MAIN THREAD SHOULD READ BOTH THE PIPES
9. A SIMPLE OPAC SYSTEM FOR LIBRARY
10. MULTI THREADED ECHO SERVER GUI CLIENT
3
4
EXNO:01 RATIONAL NUMBER
AIM:
To write a Java Program to develop a class for Rational numbers.
ALGORITHM:
Step 1:-Declare a class called Rational and invoke a function called gcd(a,b). Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function. Step 3:-Create an object for the class and declare the required string and integer variables. Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method into the object. Step 5:-Convert the input accepted into Integers through the parseInt method and store them in variables a and b. Step 6:-store the value returned by the function GCD in variable l. Step 7:-Divide a by l and b by l and store them in variables x and y.
5
PROGRAM:- 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:"+l); x=a/l; y=b/l; System.out.println(); System.out.println("The resultant value is: "+x+"/"+y); } } 6
OUTPUT:
Enter the value for A 500 Enter the value for B 1000 The GCD of the number is: 500 The resultant value is: 1/2
7
RESULT: Thus the Java program to implement Rational number was written and output was verified successfully. 8
EX NO:02 DATE CLASS IN JAVA
AIM: To design a Date class in Java.
ALGORITHM:
Step 1: Declare a class called Date example and create an object called date. Step 2:- Display the Date and Time through these objects with the Methods in Date Class. Step 3:- Declare two objects called start time and end time for this class . Step 4:- Create another object called changed object and display the changed time with the calculation Step 5:- In the main function create object for the class Date and display the time and date accordingly.
9
PROGRAM: 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 &time is:"+date); System.out.println(); System.out.println("Date object showing specificdate and time"); Date particulardate1=new Date(24L*60L*60L*1000L); Date particulardate2=new Date(0L); System.out.println(); System.out.println("first particular 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:"+strtime); Date endtime=new Date(); System.out.println("End time:"+endtime); long elapsed_time=endtime.getTime()-strtime.getTime(); System.out.println("Elapsed Time is:"+elapsed_time+"milliseconds"); System.out.println(); System.out.println("Changed date object using setTime ()method"); 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 changed date is :"+chngdate); System.out.println(); } public static void main(String args[]) { System.out.println(); DateExample(); }}
10
OUTPUT:
11
RESULT: Thus the Java program to implement Date class was written and output was verified successfully. 12
EX NO:03 IMPLEMENT LISP-LIKE LIST IN JAVA AIM:
To Implement basic operations such as 'car', 'cdr', and 'cons' using Lisp-like list in Java. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5]
ALGORITHM:
Step 1: Start the program Step 2: Create the class Lisp and declare the variables. Step 3: Generate an array using generic list method. Step 4: Use add () function to add the elements in the generic array list. Step 5: Get the values from list and store it in an object. Step 6: Implement the car () method to display the first element from the list. Step 7: Implement the cdr () method to display the all element from the list except the first element. Step 8: Implement the cons () method to add an element in the front of the list. Step 9: Stop the program.
RESULT: Thus the Lisp-Like command in java was written and output was verified successfully 18
EX NO:04 IMPLEMENTATION OF STACK ADT AIM: To write a java program to design an interface and implement ADT stack using array and linked list ALGORITHM: Step 1: Start the program. Step 2: Import the necessary packages. Step 3: Create an interface and declare methods for performing push, pop and display operations. Step 4: In Stack implementation using array program, using switch case invoke push, pop and display methods according to users choice. Step 6: In push method, obtain the element and push it at the end of array and increment the top. Step 7: In pop method, the top is decremented and the popped element is displayed. Step 8: Using loop, display the elements through array index. Step 9: In stack implementation using linked list, the methods are called from the base class. Step 10: In push method, a node is created and the element is inserted into it and linked to top. Step 11: In pop method, top node is linked to its previous node and the top node is deleted. Step 12: Using loop, display the elements of the list. Step 13: Stop the program.
19
PROGRAM: import java.io.*; class ArrayStack implements Stack { private Object [] theArray; private int topOfStack; private static final int DEFAULT_CAPACITY=10; 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()) 20
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() 21
{ if(isEmpty()) throw new UnderflowException("listStack pop"); topOfStack=topOfStack.next; } public Object top() { if(isEmpty()) throw new UnderflowException("List Stack top"); return topOfStack.element; } public Object topAndPop() { if(isEmpty()) throw new UnderflowException("ListStack top And Pop"); Object topItem=topOfStack.element; topOfStack=topOfStack.next; return topItem; } private ListNode topOfStack; } class ListNode { public Object element; public ListNode next; public ListNode(Object theElement) { this(theElement,null); } public ListNode(Object theElement,ListNode n) { element=theElement; next=n; } } interface Stack { 22
void push(Object x); void pop(); Object top(); Object topAndPop(); boolean isEmpty(); void makeEmpty(); } public 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"); 23
System.out.println("\n\n************************************** *"); 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 POP operation is happened on stack[by using linked list]"); } } } class UnderflowException extends RuntimeException { public UnderflowException(String message) { super(message); } }
24
OUTPUT:
25
RESULT: Thus the Java program to implement Stack ADT was written and output was verified successfully. 26
EX NO:05 VEHICLE CLASS HIERARCHY AIM: To write a java program to design a vehicle class hierarchy to demonstrate polymorphism.
ALGORITHM: Step 1: Start the program. Step 2: Include necessary package in java. Step 3: Create a class as vehicle. Step 4: Using class vehicle create any three sub classes. Step 5: In sub classes create vehicle name, registration no, model no, no of wheels for each. Step 6: Declare the main class as Polymorphism. Step 7: Call the subclass using main class to display the vehicle name, registration no, model no, no of leaf for each. Step 8: Stop the program.
27
PROGRAM: import java.io.*; class car extends ford { private int no; private int fuel; private int mil; private int tfuel; public car(int a,String b,int n,int f,int m) { super(a,b); fuel=f; no=n; mil=m; } public void cal(int d) { tfuel=(fuel*d)/mil; } public void display() { System.out.println("\n\nCAR"); System.out.println("Year="+year+"\nColour="+colour+"\nNo of passengers:"+no+"\n\nFuel="+tfuel+"\nMil="+mil); } } class truck extends ford { private int no; private int fuel; private int mil; private int tfuel; public truck(int a,String b,int n,int f,int m) { super(a,b); fuel=f; 28
no=n; mil=m; } public void cal(int d) { tfuel=(fuel*d)/(mil); } public void display() { System.out.println("\n\nTruck"); System.out.println("\n\nYear:"+year+"\n\nColour:"+colour+"\nNo of passengers:"+no+"\n\nFuel="+tfuel+"\n\nMileage="+mil); } } public class ford { public int year; public String colour; public ford(int a,String b) { year=a; colour=b; } public static void main(String []ar) { car c1=new car(2000,"BLACK",4,2,5); truck t=new truck(2010,"yellow",10,4,6); c1.cal(45); c1.display(); t.cal(45); t.display(); } }
29
OUTPUT:
30
RESULT: Thus the Java program to implement vehicle class hierarchy using polymorphism was written and output was verified successfully.
31
EX NO:06 OBJECT SERIALISATION
AIM: To write a program that randomly generates Rupee and Dollar objects and writes them into a file using object serialization and also to create another class to read that file,convert to Rupee if it reads a Dollar,while leaving the value as it is if it reads a Rupee. ALGORITHM: Step 1: Start the programs. Step 2: Define a class Currency as an abstract class with abstract methods. Step 3: Define the classes Rupee and Dollar as subclasses of Currency. Step 4: Define the abstract methods of the super class accordingly in each subclass. Step 5: The dollar value is converted to equivalent rupee value within a method of Dollar class. Step 6: Define a class Store Currency that randomly generates objects of Rupee and Dollar classes. Step 7: These objects are written into a file named currency using object serialization. Step 8: Define a class Read Currency that reads the objects from the file currency, and displays them. Step 9: Stop the programs.
32
PROGRAM: 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; 33
RESULT: Thus the Java program to implement the Rupee-Dollar conversion using concept of object serialization was written and output was verified successfully.
36
EX NO:07 SCIENTIFIC CALCULATOR AIM: To write a java program to design a Scientific Calculator using Event-driven Programming paradigm of Java. ALGORITHM: Step 1: Start the program. Step 2: Create a frame. Step 3: Create a panel consisting of Buttons for various scientific operations. Step 4: Set the Border layout and Grid Layout in the panel. Step 5: Create Button actions and add the buttons into the panel. Step6: Associate each Button click with the corresponding action listener. Step 7: Set the action listener for insert and command. Step 8: Perform all the calculator operations using calculator Step 9: Display the Scientific Calculator as output. Step 10: Stop the program.
37
PROGRAM: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator { public static void main(String []ar) { EventQueue.invokeLater(new Runnable() { public void run() { CalculatorFrame frame=new CalculatorFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class CalculatorFrame extends JFrame { public CalculatorFrame() { setTitle("Calculator"); CalculatorPanel panel=new CalculatorPanel(); add(panel); pack(); } } class CalculatorPanel extends JPanel { public CalculatorPanel() { setLayout(new BorderLayout()); 38
RESULT: Thus the Java program to implement Scientific Calculator using Event Driven Programming was written and output was verified successfully. 43
EXNO:08 MULTITHREADED JAVA PROGRAM AIM: To write a program in Java that prints all the prime numbers in the Fibonacci series below 10000 using multithreading. ALGORITHM: Step 1: Start the program. Step 2: Create a thread called Prime Thread that stores all the prime numbers below 10000. Step 3: Create another thread called Fibonacci Thread that stores the elements of the Fibonacci series below 10000. Step 4: Prime Thread and Fibonacci Thread are assigned a higher priority than the main thread of the program. Step 5: The main thread reads the values stored by both the threads, checks for the common elements and prints them. Step 6: Stop the program. 44
class Prime extends Thread { private PipedWriter out1 = new PipedWriter(); public PipedWriter getPipedWriter() { return out1; } public void run() { Thread t= Thread.currentThread(); t.setName("Prime"); System.out.println(t.getName() + " thread Started..."); int prime=1; while(true) { try { if(prime>100000) { out1.close(); break; } if(isPrime(prime)) out1.write(prime); prime++; sleep(0); } catch(Exception e) { System.out.println(t.getName() + " thread exiting."); System.exit(0); } } } public boolean isPrime(int n) { int m=(int)Math.round(Math.sqrt(n)); if(n==1 || n==2) return true; for(int i=2;i<=m;i++) if(n%i==0) return false; 46
return true; } } public class PipedIo { public static void main(String[] args) throws Exception { Thread t=Thread.currentThread(); t.setName("Main"); System.out.println(t.getName() + " thread Started..."); Fibonacci fibonacci = new Fibonacci(); Prime prime = new Prime(); PipedReader fpr = new PipedReader(fibonacci.getPipedWriter()); PipedReader ppr = new PipedReader(prime.getPipedWriter()); fibonacci.start(); prime.start(); int fib=fpr.read(), prm=ppr.read(); System.out.println("The numbers common to PRIME and FIBONACCI:"); while((fib!=-1) && (prm!=-1)) { while(prm<=fib) { if(fib==prm) System.out.println(prm); prm=ppr.read(); } fib=fpr.read(); } System.out.println(t.getName() + " thread exiting"); } }
47
OUTPUT:
48
RESULT:
Thus the Multithreaded java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13,etc)was written and output was verified successfully.
49
EX NO:09 DATABASE CONNECTIVITY USING OPAC AIM: To write a java program using open public access catalog for library management system along with GUI environment ALGORITHM: Step 1: Start the Process Step 2: Using Java Swing Setup the graphical user interface for OPAC library management systems Step 3: Select the parameters that will be required for searching books using OPAC Step 4: Organize the parameters as labels, textboxes, dropdown list, buttons. Step 5: Using Event handling technique set up the query for searching books in database Step 6: Establish JDBC Connection . Step 7: Create an Object for Connection, Statement class Step 8: Using the connection object, the authentication can be established between the Database and the program Step 9: Using the Statement object, the statements that has to be updated in the datatbase are carried out and the result for the query is returned in the GUI window. Step 10:Stop the process
} } } class prog1 { public static void main(String args[]) { Ja j=new Ja(); j.myput(); } }
52
OUTPUT:
53
RESULT: Thus the java program to implement database connectivity using OPAC system was written and output was written successfully.
54
EX NO:10 MULTITHREADED ECHO SERVER- CLIENT IN JAVA
AIM: To develop a Java Program that supports multithreaded echo server and a GUI client. ALGORITHM: Step 1: Import the net package which supports networking features in Java. Step 2: Write the input data into an object from the keyboard through BufferedStream class. Step 3: Create a new object for Socket s and Write the input data into another object called dos using writeBytes() method. Step 4: Read the copied string into br using readLine() method and close the file. Step 5: On executing the program,the server sends a message to the client. Step 6: For the server side program, create an object for ServerSocket class and write input data into it. Step 7: Write the data into the dataoutputstream object dos. Step 8: Close the object and socket. Step 9: Set up a GUI envrionment for server and client using Swing Step 10: Interconnect the GUI environment with the eventhandling processs for carrying messages from client to server Step 11: Stop the process.
55
PROGRAM: Server program: import java.net.*; import java.io.*; class Server { public static void main(String args[])throws IOException { ServerSocket ss=null; try { ss=new ServerSocket(95); } catch(IOException ioe) { System.out.println("Error finding port"); System.exit(1); } Socket soc=null; try { soc=ss.accept(); System.out.println("Connection accepted at:"+soc); } catch(IOException ioe) { System.out.println("Server failed to accept"); System.exit(1); } DataOutputStream dos=new DataOutputStream(soc.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(soc.getInputStream())); String s; System.out.println("Server is waiting for message from the client"); 56
soc=new Socket(InetAddress.getLocalHost(),95); br=new BufferedReader(new InputStreamReader(soc.getInputStream())); dos=new DataOutputStream(soc.getOutputStream()); } catch(UnknownHostException uhe) { System.out.println("Unknown Host"); System.exit(0); } System.out.println("To start the dialog type the message in the client window\n Type exit to end"); boolean more=true; while(more) { str=kyrd.readLine(); dos.writeBytes(str); dos.write(13); dos.write(10); dos.flush(); String s,s1; s=br.readLine(); System.out.println("From server:"+s); if(s.equals("exit")) break; } br.close(); dos.close(); soc.close(); } }
58
OUTPUT:
59
RESULT: Thus the java program to implement Multithreaded echo server client using GUI Environment was written and output was verified successfully. 60
61
62
63
64
TRY THIS..( VIVA Questions) 1. Why java is Secured Compare with other Language? 2. What if the main method is declared as private? 3. What if the static modifier is removed from the signature of the main method? 4. What if I write static public void instead of public static void? 5. What if I do not provide the String array as the argument to the method? 6. What is the first argument of the String array in main method? 7. If I do not provide any arguments on the command line, then the String array of Main method will be empty or null? 8. What environment variables do I need to set on my machine in order to be able to run Java programs? 9. Can an application have multiple classes having main method? 10. In how many Ways we can create a Object in java? 11. Every Application Should ve a main() Method under which class does the main() Method come Under? 12. What is Difference Between Static And Dynamic Polymarphism? 13. What happens If public Static void main() is made protected? 14. Can we Override the Main() Method? 15. What is the name of the java Complier used to compile the Source File to byte code? 16. what is the use of static data member? 17. What does "wrapping" an object mean? 18. What is the difference between a while statement and a do statement? 19. What is Constructor? 20. How are this() and super() used with constructors? 21. What is Difference between the Constructor and the Method? 22. What is the need of calling Default Constructor? 23. What is Difference between Instance and the Object? 24. What is System.Out.Println means? 25. What is JTI (Just in time) Engine means? 26. What is Differences Between Static & Final? 27. What is the difference between static and non-static variables? 28. What is Differences Between class and Package? 29. What is String class? 30. What is Scanner Class in java? 31. What will a Static Variables is loaded ? Is at Compile time or Run Time www.vidyarthiplus.com 32. What are the Primitive Types in java? 33. What is the difference between an Interface and an Abstract class? 34. What is the purpose of garbage collection in Java, and when is it used? 35. What is the difference between a constructor and a method? 36. What is an Iterator? 37. State the significance of public, private, protected, default modifiers 65
both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. 38. What is an abstract class? 39. What is static in java? 40. What is final ? 41. What are pass by reference and passby value? 42. Can I have multiple main methods in the same class? 43. How can one prove that the array is not null but empty using one line of code? 44. Do I need to import java.lang package any time? Why ? 45. Can I import same package/class twice? Will the JVM load the package twice at runtime? 46. What are Checked and UnChecked Exception? 47. What is Overriding? 48. What are different types of inner classes? 49. Does Java provide any construct to find out the size of an object? 50. What are wrapper classes? 51. Why do we need wrapper classes? 52. What are checked exceptions? 53. What are runtime exceptions? 54. What is the difference between error and an exception?? Question: How to create custom exceptions? 55. If I want an object of my class to be thrown as an exception object, what should I do? 56. If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? 57. How does an exception permeate through the code? 58. What are the different ways to handle exceptions? 59. What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause hen should you use which approach? 60. Is it necessary that each try block must be followed by a catch block? 61. If I write return at the end of the try block, will the finally block still execute?If I write System.exit (0); at the end of the try block, will the finally block still execute? 62. Are the imports checked for validity at compile time? e.g. will the www.vidyarthiplus.com code containing an import such as java.lang.ABCD compile? 63. Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*? 64. What is the difference between declaring a variable and defining a variable? 65. What is the default value of an object reference declared as an instance variable? 66. Can a top level class be private or protected? 67. What type of parameter passing does Java support? 68. Primitive data types are passed by reference or pass by value? 69. Objects are passed by value or by reference? 70. What is serialization? 66
71. How do I serialize an object to a file? 72. What happens to the static fields of a class during serialization? 73. Describe synchronization in respect to multithreading. 74. Explain different way of using thread? 75. What is HashMap and Map? 76. Difference between HashMap and HashTable? 77. Difference between Vector and ArrayList? 78. Difference between Swing and Awt? 79. What is synchronization and why is it important? 80. Does garbage collection guarantee that a program will not run out of memory? 81. How does Java handle integer overflows and underflows? 82. What is the difference between preemptive scheduling and time slicing? 83. When a thread is created and started, what is its initial state? 84. What is the purpose of finalization? 85. What is the Locale class? 86. What are synchronized methods and synchronized statements? 87. What is daemon thread and which method is used to create the daemon thread? 88. Can applets communicate with each other?