Ex No1: Rational Numbers 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.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Ex No1: Rational Numbers
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.
Program:-
import java.io.*;class rational1{
public rational1(){}
public long gcd(long a,long b){
if(b==0)return a;
elsereturn 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);
}}
Output
Enter the value for A500Enter the value for B1000
The GCD of the number is:500
The resultant value is: 1/2Ex No 2: Date Class in Java
AIM
To design a Date class in Java .
ALGORITHM:-
Step 1:Declare a class called Dateexample and create an object called date.
Step 2:-Display the Date and Time through these objects with theMethods in Date Class.
Step 3:-Declare two objects called starttime and endtime for this class .
Step 4:-Create another object called changed object and display the changed time with the calculation 24L*60L*60L*1000L.
Step 5:-In the main function create object for the class Date and display the time and date accordingly.
SOURCE CODE
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();
me");
te1);
te2);
System.out.println("Date object showing specific date and ti
Date particulardate1 = new Date(24L*60L*60L*1000L); Date particulardate2 = new Date(0L); System.out.println();System.out.println("First Particular date : " + particularda
System.out.println("Demo of getTime() method returning milli seconds");
System.out.println();Date strtime = new Date(); System.out.println("Start Time: " + 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 + " mil
liseconds"); System.out.println();
od");
}
System.out.println("Changed date object using setTime() meth
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 date is: " + chngdate); System.out.println();
public static void main(String[] args) { System.out.println();DateExample();
}
}
OUTPUT
Current Date and Time is : Mon Dec 10 18:39:27 GMT+05:302007
Date object showing specific date and time
First Particular date : Fri Jan 02 05:30:00 GMT+05:30 1970Second Particular date: Thu Jan 01 05:30:00 GMT+05:30 1970
Demo of getTime() method returning milliseconds
Start Time: Mon Dec 10 18:39:28 GMT+05:30 2007End Time is: Mon Dec 10 18:39:28 GMT+05:30 2007Elapsed Time is:0 milliseconds
Changed date object using setTime() method
Date before change is: Mon Dec 10 18:39:28 GMT+05:30 2007Now the Changed date is: Fri Jan 02 05:30:00 GMT+05:30 1970
Ex4 : Implementation of Stack ADT
AIM
To write a Java Program to design an interface for StackADT.and implement Stack ADT using both Array and Linked List.
ALGORITHM
Step 1:Declare an array for storing the stack elements and initialise the capacity of the array.
Step 2:-Declare functions makeempty(),isempty() to check whether the stack is empty to insert an element.
Step 3:After inserting an element,increment the counter by 1 to increase the number of elements in stack.
Step 4:Initiate another array to extend the size of the array when the number of elements exceed beyond the limit.
Step 5:-Invoke methods and constructors to implement the stack using linked list.
Step 6:-Test if the stack is logically empty.then return true or else false.
Step 7:To delete an element from stack,check if stack is empty,if so throw an exception or else move to the next element in the stack.
Step 8:To return the most recently inserted element use the method topOfStack() and then move the pointer to the next element.
Step 9:Declare a stack Interface to push and pop elements from stack.
Step 10:create two objects one for array and other for linked list implementation of stack.
Step 11:Insert characters and numbers into the stack using the methods and display the inserted elements with exception blocks.
SOURCE CODE
/*** Array-based implementation of the stack.
*/public class ArrayStack implements Stack {
private Object [ ] theArray;private int topOfStack;private static final int DEFAULT_CAPACITY = 10;
/*** Construct the stack.*/public ArrayStack( ) {
theArray = new Object[ DEFAULT_CAPACITY ];topOfStack = -1;
}
/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/public boolean isEmpty( ) {
return topOfStack == -1;}
/*** Make the stack logically empty.*/public void makeEmpty( ) {
topOfStack = -1;}
/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/public Object top( ) {
if( isEmpty( ) )throw new UnderflowException( "ArrayStack top" );
return theArray[ topOfStack ];}
/*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.*/public void pop( ) {
if( isEmpty( ) )throw new UnderflowException( "ArrayStack pop" );
topOfStack--;}
/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @throws Underflow if the stack is empty.*/public Object topAndPop( ) {
/*** Internal method to extend theArray.*/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;
}
}
//ListStack class//// CONSTRUCTION: with no initializer//// ******************PUBLIC OPERATIONS*********************// void push( x ) --> Insert x// void pop( ) --> Remove most recently inserted item// Object top( ) --> Return most recently inserted item// Object topAndPop( ) --> Return and remove most recent item// boolean isEmpty( ) --> Return true if empty; else false// void makeEmpty( ) --> Remove all items// ******************ERRORS********************************// top, pop, or topAndPop on empty stack
/*** List-based implementation of the stack.
*/public class LinkedListStack implements Stack {
/*** Construct the stack.*/
public LinkedListStack( ) {topOfStack = null;
}
/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/
public boolean isEmpty( ) {return topOfStack == null;
}
/*** Make the stack logically empty.*/
public void makeEmpty( ) {topOfStack = null;
}
/*** Insert a new item into the stack.* @param x the item to insert.*/
public void push( Object x ) {topOfStack = new ListNode( x, topOfStack );
}
/*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.
*/public void pop( ) {
if( isEmpty( ) )throw new UnderflowException( "ListStack pop" );
topOfStack = topOfStack.next;}
/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/
public Object top( ) {if( isEmpty( ) )
throw new UnderflowException( "ListStack top" );return topOfStack.element;
}
/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/
public Object topAndPop( ) {if( isEmpty( ) )
throw new UnderflowException( "ListStack topAndPop");
public ListNode( Object theElement, ListNode n ) {element = theElement;
next = n;}
}
public interface Stack {/*** Insert a new item into the stack.* @param x the item to insert.*/
void push( Object x );
/*** Remove the most recently inserted item from the stack.* @exception UnderflowException if the stack is empty.*/
void pop( );
/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/
Object top( );
/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/
Object topAndPop( );
/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/
boolean isEmpty( );
/*** Make the stack logically empty.*/
void makeEmpty( );
}
public class StackTester {
public static void main(String[] args) {
System.out.println("******************************************"); System.out.println("Stack using Array & Linked List
}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
operation is happened on Stack[by using linked list]");}
}}
/*** Exception class for access in empty containers* such as stacks, queues, and priority queues.* @author Ramkumar*/
public class UnderflowException extends RuntimeException {/*** Construct this exception object.* @param message the error message.*/
public UnderflowException( String message ) {super( message );
}}
OUTPUT
Stack using Array & Linked List example****************************************** Stack[using array] elements -> a, b, c Stack LIFO and POP -> cStack LIFO -> bException occured while POP operation is happened on Stack[by using array]
****************************** Stack using Linked List example******************************Stack[using linked list] elements -> 10, 20, 30, 40Stack TOP ->40Stack TOP after POP ->30Exception occured while POP operation is happened on Stack[by using linked list]
Ex no:5 Polymorphism
Aim:- To develop a vehicle class hierarchy in Java to demonstrate the concept of polymorphism.
Algorithm:-
Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.
Step 2:-Derive another class called car and invoke a function tostring() to display the variables.
Step 3:-Derive another class called motorcycle with same data and method called setseats() .
Step 4:-Declare another sub class called Truck with 2 constructors and finally assign values to variables.
Step 5:-In the main function, create an object for class motorcycle and display all details of sub classes through object.
Sourcecode:-
//This is the class that will be inherited public class Vehicle{
public int doors; public int seats; public int wheels; Vehicle(){
wheels=4; doors=4; seats=4;
}}//This class inherits Vehicle.java public class Car extends Vehicle{
public String toString()
{return "This car has "+seats+" Seats, "+doors+" Doors "+
"and "+wheels+" wheels.";}
}//This class inherits Vehicle.java public class MotorCycle extends Vehicle{
return "This "+(isPickup?"pickup":"truck")+" has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+"
wheels.";}
}//This class tests the classes that inherit Vehicle.javapublic class VehiclesTest{
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
This motorcycle has 1 Seats, 0 Doors and 2 wheelsThis car has 4 Seats, 4 Doors and 4 wheels This car has 4 Seats, 2 Doors and 4 wheels This pickup has 4 Seats, 4 Doors and 4 wheels This truck has 4 Seats, 2 Doors and 4 wheels
Ex No:-6 Object Serialization
Aim:-To write a Java Program to randomly generate objects and write them into a file using concept of Object Serialization.
Algorithm:-
Step 1:Declare a class called Currency .Open a file in output mode with a name.
Step 2:-Write new data into the object using writeobject() method.
Step 3:-Similarly create an input stream object .Read it both in terms of Dollars andRupees.close the output object.
Step 4:-derive a class called Dollar which implements serializable interface.Invoke a constructor and function to display the data.
Step 5:Similarly declare a class called Rupee with private variables and use print function to display the variables.
Step 6:terminate the execution.The output is displayed as dollar to rupee conversion and vice versa.
Sourcecode:-
// Currency conversion import java.io.*;public class Currency{
To develop a scientific calculator using even-driven programming paradigm of Java.
ALGORITHM:
Step 1:-Import all the packages required for designing the graphical elements in the applet window.
Step 2:-Implement the Listener files for Keyboard, mouse events in the class defined.
Step 3:-Import the swing package in the program for using swing components for thr gridLayout design for menu,Frame,Dialog,TextArea,Label and other components for alignment in the appletwindow.
Step 4:-Create objects from the main classes forJLabel,Jtextbox,JPanel ,Font and Menu items.
Step 5:Assign the font items to all the menu items and add them to the panel.
Step 6:-Create the GridBagLayout and add all the buttons to it using the swing class.
Step 7:-Add all the JButtons to the panel and also the colour components to the GUI controls.
Step 8:-Call adddighitstodisplay() to activate the required arithmetic operations when the buttons are pressed.
Step 9:Invoke the function displayresult() to store the result of the values computed.
Step 10:-Handle the divide by zero exception outside the class definition. And create an object for the class created.
Step 11:-Add all the methods,properties and layout to the panel window and display the result in the textarea created.
Step 12:-Invoke the actionPerformed() method through the ActionEvent class and write code for each operator or number being pressed.
// Add components to frame getContentPane().add(jlbOutput, BorderLayout.NORTH);
jbnButtons = new JButton[23];// GridLayout(int rows, int cols, int hgap, int vgap)
JbuttonsJPanel jplButtons = new JPanel(); // container for
// Create numeric Jbuttons for (int i=0; i<=9; i++){
// set each Jbutton label to the value of index jbnButtons[i] = new JButton(String.valueOf(i));
}
// Create operator Jbuttons jbnButtons[10] = new JButton("+/-"); jbnButtons[11] = new JButton("."); jbnButtons[12] = new JButton("="); jbnButtons[13] = new JButton("/"); jbnButtons[14] = new JButton("*"); jbnButtons[15] = new JButton("-"); jbnButtons[16] = new JButton("+"); jbnButtons[17] = new JButton("sqrt"); jbnButtons[18] = new JButton("1/x"); jbnButtons[19] = new JButton("%");
jplBackSpace = new JPanel();jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
jbnButtons[20] = new JButton("Backspace");jplBackSpace.add(jbnButtons[20]);
jplControl = new JPanel();jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
jbnButtons[21] = new JButton(" CE ");jbnButtons[22] = new JButton("C");
public void actionPerformed(ActionEvent e){if(e.getSource() == jbnOk) {this.dispose();}}
}
OUTPUT
EX NO:-8 Multithreading
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:
Step 1:-Include Dataoutputstream and pipedOutputStreamClasses in the program to accept numbers as input from user.
Step 2:-Create an object for class DataOutputStream to display the data.
Step 3:-Invoke the run() method to initiate the FOR loop and write the data into the object.
Step 4:Create a function called Fibonacci() and assign the previous,next and final values to display the series.
Step 5:-Create two objects for PipedInputStream and PipedOutputStream and inherit from the Thread class to generate prime numbers.
Step 6:Start the threads and handle the exceptions through the try-catch block.
Step 7:-Call the super class method in the subclass and give the code to check for the condition required for a number to be prime inside the run() method of the Thread class.
Step 8:-Write the list of prime numbers into the object created.Create another thread using the Thread class to write the Fibonacci series into another pipe.
Step 9:-Call the main thread in the main function through the ThreadGroup and read the data from the two separate objects for Fibonacci numbers and prime numbers.Identify the
PipedOutputStream pos, String name){super(threadGroup, name);dos = new DataOutputStream(pos);
}
@Overridepublic void run() {
try {int x, y, c = 0;for( x = 2; x < 10000; x++ ){
if( x % 2 != 0 || x == 2 ){for( y = 2; y <= x / 2; y++ ){
if( x % y == 0 ){break;
}}if( y > x / 2 ){
if(x < 10000){ dos.writeLong(x); dos.flush();
}}
}}
} catch (IOException e) {}
}}
OUTPUT
Fibonic Number #>1Prime Number #>2Fibonic Number #>1Prime Number #>3Fibonic Number #>2Prime Number #>5Fibonic Number #>3Prime Number #>7Fibonic Number #>5Prime Number #>11Fibonic Number #>8Prime Number #>13Fibonic Number #>13Prime Number #>17Fibonic Number #>21Prime Number #>19Fibonic Number #>34Prime Number #>23Fibonic Number #>55Prime Number #>29
Fibonic Number #>89Prime Number #>31Fibonic Number #>144Prime Number #>37Fibonic Number #>233Prime Number #>41Fibonic Number #>377Prime Number #>43Fibonic Number #>610Prime Number #>47Fibonic Number #>987Prime Number #>53Fibonic Number #>1597Prime Number #>59Fibonic Number #>2584Prime Number #>61Fibonic Number #>4181Prime Number #>67Fibonic Number #>6765Prime Number #>71Prime Number #>73Prime Number #>79Prime Number #>83Prime Number #>89Prime Number #>97Prime Number #>101Prime Number #>103Prime Number #>107Prime Number #>109Prime Number #>113Prime Number #>127Prime Number #>131Prime Number #>137Prime Number #>139Prime Number #>149Prime Number #>151Prime Number #>157Prime Number #>163Prime Number #>167Prime Number #>173Prime Number #>179Prime Number #>181Prime Number #>191Prime Number #>193Prime Number #>197Prime Number #>199Prime Number #>211Prime Number #>223Prime Number #>227Prime Number #>229Prime Number #>233Prime Number #>239
Prime Number #>241Prime Number #>251Prime Number #>257Prime Number #>263Prime Number #>269Prime Number #>271Prime Number #>277Prime Number #>281Prime Number #>283Prime Number #>293Prime Number #>307Prime Number #>311Prime Number #>313Prime Number #>317Prime Number #>331Prime Number #>337
Ex No:9 Java Database Connectivity
Aim:-To develop a simple OPAC System for library management system using event-driven and concurrent programming paradigms and java database connectivity.
Algorithm:-
Step 1:Initiate a class and declare the driver for the Driver name required to connect to the database.
Step 2:-Enclose the coding in a try block to handle errors and trap the exception in a catch block.
Step 3:-Establish the connection object to connect to the backend.
Step 4:-Create an object for Statement object using createStatement() object.
Step 5:-Issue a query through executeQuery() method.
E:\java>java ServerConnection accepted at :Socket[addr=/127.0.0.1,port=49442,localport=95] Server waiting for message from tthe clientFrom client :helloFrom client :how are you From client :how are you From client :exit