Académique Documents
Professionnel Documents
Culture Documents
ALGORITHM:
Step 3:-Create an object for the class and declare the required
string and integer variables.
import java.io.*;
class rational1
{
public rational1(){}
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
AIM
ALGORITHM:-
Step 2:-Display the Date and Time through these objects with the
Methods in Date Class.
Step 3:-Declare two objects called starttime and endtime for this
class .
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();
System.out.println("Date object showing specific date and ti
me");
Date particulardate1 = new Date(24L*60L*60L*1000L);
Date particulardate2 = new Date(0L);
System.out.println();
System.out.println("First Particular date : " + particularda
te1);
System.out.println("Second Particular date: " + particularda
te2);
System.out.println();
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();
System.out.println("Changed date object using setTime() meth
od");
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
AIM
ALGORITHM
Step 8:To return the most recently inserted element use the
method topOfStack() and then move the pointer to the next
element.
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 {
/**
* 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( ) {
if( isEmpty( ) )
throw new UnderflowException( "ArrayStack topAndPop" );
return theArray[ topOfStack-- ];
}
/**
* Insert a new item into the stack.
* @param x the item to insert.
*/
public void push( Object x ) {
if( topOfStack + 1 == theArray.length )
doubleArray( );
theArray[ ++topOfStack ] = x;
}
/**
* Internal method to extend theArray.
*/
private void doubleArray( ) {
Object [ ] 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"
);
// Constructors
public ListNode( Object theElement ) {
this( theElement, null );
}
/**
* 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( );
System.out.println("******************************************");
System.out.println("Stack using Array & Linked List
example");
System.out.println("******************************************");
/**
* 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 Linked List example
******************************
Stack[using linked list] elements -> 10, 20, 30, 40
Stack TOP ->40
Stack TOP after POP ->30
Exception occured while POP operation is happened on Stack[by
using linked list]
Ex no:5 Polymorphism
Algorithm:-
Sourcecode:-
}
}
Output
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 and
Rupees.close the output object.
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
{
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:-
E:\java>java Currency
$40.0
Rs.50.0
$40.0
Rs.50.0
Ex No:7 Event-Driven Programming
AIM
ALGORITHM:
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 applet
window.
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 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.
SOURCE CODE:=-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
// Variables
/*
* Font(String name, int style, int size)
Creates a new Font from the specified name, style and point
size.
*/
// Constructor
public Calculator()
{
/* Set Up the JMenuBar.
* Have Provided All JMenu's with Mnemonics
* Have Provided some JMenuItem components with Keyboard
Accelerators
*/
jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,
ActionEvent.CTRL_MASK));
jmenuFile.add(jmenuitemExit);
setBackground(Color.gray);
jplControl.add(jbnButtons[21]);
jplControl.add(jbnButtons[22]);
if (i<10)
jbnButtons[i].setForeground(Color.blue);
else
jbnButtons[i].setForeground(Color.red);
}
// Second row
for(int i=4; i<=6; i++)
{
jplButtons.add(jbnButtons[i]);
}
// Third row
for( int i=1; i<=3; i++)
{
jplButtons.add(jbnButtons[i]);
}
//Fourth Row
// add 0, +/-, ., +, and =
jplButtons.add(jbnButtons[0]);
jplButtons.add(jbnButtons[10]);
jplButtons.add(jbnButtons[11]);
jplButtons.add(jbnButtons[16]);
jplButtons.add(jbnButtons[12]);
jplMaster.setLayout(new BorderLayout());
jplMaster.add(jplBackSpace, BorderLayout.WEST);
jplMaster.add(jplControl, BorderLayout.EAST);
jplMaster.add(jplButtons, BorderLayout.SOUTH);
jmenuitemAbout.addActionListener(this);
jmenuitemExit.addActionListener(this);
clearAll();
// Perform action
public void actionPerformed(ActionEvent e){
double result = 0;
if(e.getSource() == jmenuitemAbout){
JDialog dlgAbout = new CustomABOUTDialog(this,
"About Java Swing
Calculator", true);
dlgAbout.setVisible(true);
}else if(e.getSource() == jmenuitemExit){
System.exit(0);
}
case 1:
addDigitToDisplay(i);
break;
case 2:
addDigitToDisplay(i);
break;
case 3:
addDigitToDisplay(i);
break;
case 4:
addDigitToDisplay(i);
break;
case 5:
addDigitToDisplay(i);
break;
case 6:
addDigitToDisplay(i);
break;
case 7:
addDigitToDisplay(i);
break;
case 8:
addDigitToDisplay(i);
break;
case 9:
addDigitToDisplay(i);
break;
case 12: // =
processEquals();
break;
case 14: // *
processOperator("*");
break;
case 15: // -
processOperator("-");
break;
case 16: // +
processOperator("+");
break;
result = Math.sqrt(getNumberInDisplay());
displayResult(result);
}
catch(Exception ex)
{
displayError("Invalid input for function!”);
displayMode = ERROR_MODE;
}
}
break;
result = 1 /
getNumberInDisplay();
displayResult(result);
}
catch(Exception ex) {
displayError("Cannot
divide by zero!");
displayMode =
ERROR_MODE;
}
}
break;
case 19: // %
if (displayMode != ERROR_MODE){
try {
result =
getNumberInDisplay() / 100;
displayResult(result);
}
catch(Exception ex) {
displayError("Invalid
input for function!");
displayMode =
ERROR_MODE;
}
}
break;
setDisplayString(getDisplayString().substring(0,
getDisplayString().length() - 1));
if
(getDisplayString().length() < 1)
setDisplayString("0");
}
break;
case 21: // CE
clearExisting();
break;
case 22: // C
clearAll();
break;
}
}
}
}
if (inputString.indexOf("0") == 0){
inputString = inputString.substring(1);
}
displayMode = INPUT_MODE;
clearOnNextDigit = false;
}
void addDecimalPoint(){
displayMode = INPUT_MODE;
if (clearOnNextDigit)
setDisplayString("");
void processSignChange(){
if (displayMode == INPUT_MODE)
{
String input = getDisplayString();
else
setDisplayString("-" + input);
}
if (numberInDisplay != 0)
displayResult(-numberInDisplay);
}
}
void clearAll() {
setDisplayString("0");
lastOperator = "0";
lastNumber = 0;
displayMode = INPUT_MODE;
clearOnNextDigit = true;
}
void clearExisting(){
setDisplayString("0");
clearOnNextDigit = true;
displayMode = INPUT_MODE;
}
double getNumberInDisplay() {
String input = jlbOutput.getText();
return Double.parseDouble(input);
}
if (!lastOperator.equals("0"))
{
try
{
double result = processLastOperator();
displayResult(result);
lastNumber = result;
}
catch (DivideByZeroException e)
{
}
}
else
{
lastNumber = numberInDisplay;
}
clearOnNextDigit = true;
lastOperator = op;
}
}
void processEquals(){
double result = 0;
if (displayMode != ERROR_MODE){
try
{
result = processLastOperator();
displayResult(result);
}
catch (DivideByZeroException e) {
displayError("Cannot divide by zero!");
}
lastOperator = "0";
}
}
if (lastOperator.equals("/"))
{
if (numberInDisplay == 0)
throw (new DivideByZeroException());
if (lastOperator.equals("*"))
result = lastNumber * numberInDisplay;
if (lastOperator.equals("-"))
result = lastNumber - numberInDisplay;
if (lastOperator.equals("+"))
result = lastNumber + numberInDisplay;
return result;
}
public DivideByZeroException(String s)
{
super(s);
}
}
p1.add(jtAreaAbout);
p1.setBackground(Color.red);
getContentPane().add(p1, BorderLayout.CENTER);
p2.add(jbnOk);
getContentPane().add(p2, BorderLayout.SOUTH);
setLocation(408, 270);
setResizable(false);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
Window aboutDialog = e.getWindow();
aboutDialog.dispose();
}
}
);
pack();
}
OUTPUT
EX NO:-8 Multithreading
Aim:-
ALGORITHM:
Step 3:-Invoke the run() method to initiate the FOR loop and
write the data into the object.
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.
SOURCE CODE
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedOutputStream;
@Override
public void run() {
try {
for(int k=0; k<10000; k++){
long fibonacciNum = fib(k);
if(fibonacciNum > 0L && fibonacciNum <
10000L){
dos.writeLong(fibonacciNum);
dos.flush();
}
}
} catch (IOException e) {
}
}
}
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
DataInputStream fibonicPis;
DataInputStream primePis;
} catch (IOException e) {
e.printStackTrace();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
boolean canRun = true;
boolean canGoPrimeLoop = true;
boolean canGoFibonicLoop = true;
Long primeNumber = -1L;
Long fibonacciNumber = -1L;
while(canRun){
try {
fibonacciNumber = fibonicPis.readLong();
System.out.println(" Fibonic Number
#>"+fibonacciNumber);
} catch (IOException e) {
//System.err.println("Exception occurred
while reading from fibonacci number, "+e);
canGoFibonicLoop = false;
}
}
} catch (IOException e) {
//System.err.println("Exception occurred
while reading from prime number, "+e);
canGoPrimeLoop = false;
}
}
}
}
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedOutputStream;
} catch (IOException e) {
}
}
}
OUTPUT
Algorithm:-
Step 1:Initiate a class and declare the driver for the Driver
name required to connect to the database.
Source code:-
Import java.awt.*;
Import javax.swing.*;
Import java.awt.event.*;
Import java.sql.*;
Public class Jdbcapplet extends JApplet implements
ActionListener,ItemListener
{
JTextField t1,t2;
Container contentPane=getContentPane();
JLabel l1,l2,l3;
JButton save;
JPanel p1,p2;
JCheckBox c[];
String selected=””;
Public void init()
{contentPane.setLayout(new FlowLayout());
T1=new JTextField(20);
T2=new JTextField(20);
L1=new JLabel(“enter name:”);
L2=new JLabel(“enter occupation”);
P1=new JPanel();
P1.setLayout(new GridLayout(2,2));
P1.add(l1);
P1.add(t1);
P1.add(l2);
P1.add(t2);
P2=new JPanel();
P2.setLayout(new GridLayout(8,1));
P2.add(new JLabel(“which os do u use?”));
C=new JCheckbox[6];
For(int i=0;i<=5;i++)
{
C[i]=new JCheckBox(“”,false);
P2.add(c[i]);
C[i].addItemListener(this);
}
C[0].setText(“complete reference”);
;
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.
// Client Program:-
import java.net.*;
import java.io.*;
class Client
{
public static void main(String args[])throws IOException
{
Socket soc=null;
String str=null;
BufferedReader br=null;
DataOutputStream dos=null;
BufferedReader kyrd=new BufferedReader(new InputStreamReader(System.in));
try
{
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 this 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();
}
}
Output:-
E:\java>java Client
To start the dialog type the message in this client window
Type exit to end
hello
From server :hello
// 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 waiting for message from tthe client");
boolean quit=false;
do
{
String msg="";
s=br.readLine();
int len=s.length();
if(s.equals("exit"))
quit=true;
for(int i=0;i<len;i++)
{
msg=msg+s.charAt(i);
dos.write((byte)s.charAt(i));
}
System.out.println("From client :"+msg);
dos.write(13);
dos.write(10);
dos.flush();
}while(!quit);
dos.close();
soc.close();
}
}
Output:-
E:\java>java Server
Connection accepted at :Socket[addr=/127.0.0.1,port=49442,localport=95]
Server waiting for message from tthe client
From client :hello
From client :how are you
From client :how are you
From client :exit