Java Lab
Java Lab
Java Lab
AIM
To write a JAVA program for finding simplified form of the given rational number.
ALGORITHM
1. Import java.util and java.io package.
2. Define Rational class with required variables .
3. Get the numerator and denominator values.
4. Using the object of the Rational class call the method efficientrep().
5. If the numerator is greater than the denominator
then i). Return the input as it is.
Else
i). Find the Rational value.
ii). Return (numerator+"/"+denominator).
6. Display the Simplified form of rational number on screen like numerator/denominator.
REVIEW QUESTIONS
1. What is Bytecode?
Each java program is converted into one or more class files. The content of the
class
file is a set of instructions called bytecode to be executed by Java Virtual
Machine
(JVM).Java introduces bytecode to create platform independent program.
2. What is JVM?
JVM is an interpreter for bytecode which accepts java bytecode and produces
result.
PROGRAM
rational_main.java
import java.util.Scanner;
class rational_main
{
/** Class that contains the main function
* @author Vivek Venkatesh (Your name)
*/
public static void main(String args[])
{
/** Create an instance of "rational" class
* to call the function in it.
*/
rational x = new rational();
//To get input from user
Scanner s = new Scanner(System.in);
int a,b;
System.out.println("\n Enter the Numerator and Denominator:");
a = s.nextInt();
b = s.nextInt();
x.efficient_rep(a,b);
}
}
rational.java
public class rational
{
/** Rational number class
* To give an efficient representation of user's input rational number
* For ex: 500/1000 to be displayed as 1/2
*/
public void efficient_rep(int a, int b)
{
int x=b;
if(a=2;i--)
{
if(a%i==0 && b%i==0)
{
a=a/i;
b=b/i;
}
}
System.out.println(a + "/" + b);
}
}
RESULT
Thus the java program for finding simplified form of the given rational number
was compiled and executed successfully.
EX NO:1.2) FIBONACCI
SERIES DATE:
AIM
To write a JAVA program for finding first N Fibonacci numbers.
ALGORITHM
1. import java.io package.
2. Length of Fibonacci series „N‟ must be got as a keyboard input by using
InputStreamReader class.
BufferedReader br=new BufferedReader(new InputStreamReader(System.in))
3. Convert the input into an integer using parseInt( ) method which is available in Integer
class.
4. Declare two integer data type variables F1 & F2 and assign values as F1=-1 & F2=1.
5. FOR i=1 to N do the following
FIB= F1 + F2
F1 = F2
F2 =FIB
PRINT FIB
END FOR
6. Stop the Program.
REVIEW
QUESTIONS
1. What is class?
A class is a blueprint or prototype from which objects are created. We can create
any number of objects for the same class.
2. What is object?
Object is an instance of class. Object is real world entity which has state, identity
and behavior.
4. What is encapsulation?
Encapsulation is the mechanism that binds together code and the data it
manipulates,
and keeps both safe from outside interference and misuse.
class fibb
{
num=Integer.parseInt(JOptionPane.showInputDialog("Enter Number:"));
if(num>1)
{
for(i=2;i<=num;i++)
{
fib[i]=fib[i-1]+fib[i-2];
}
}
String str="";
for(i=0;i<num;i++)
str=str + " " +fib[i];
JOptionPane.showMessageDialog(null, str);
RESULT
Thus the java program for finding first N Fibonacci numbers was compiled and
executed successfully.
EX NO:1.3) PRIME NUMBER
CHECKING DATE:
AIM
To write a JAVA program that reads an array of N integers and print whether each one
is
prime or not.
ALGORITHM
Method IsPrime is returns Boolean value. If it is Prime then return true otherwise return false.
REVIEW QUESTIONS
1. What is casting?
Casting is used to convert the value of one data type to another.
2. What is a package?
A package is a collection of classes and interfaces that provides a high-level layer
of
access protection and name space management.
PROGRAM
import java.util.Scanner;
/**
* Simple Java program to print prime numbers from 1 to 100 or any number.
* A prime number is a number which is greater than 1 and divisible
* by either 1 or itself.
*/
public class PrimeNumberExample {
/*
* Prime number is not divisible by any number other than 1 and itself
* @return true if number is prime
*/
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
RESULT
Thus the java program for checking prime number was compiled and executed
successfully.
EX NO:2) LEAP YEAR
CALCULATION DATE:
AIM
To write a JAVA program for finding whether the given year is a leap year or not.
ALGORITHM
REVIEW
QUESTIONS
7. What is class?
A class is a blueprint or prototype from which objects are created. We can create any
number of objects for the same class.
8. What is object?
Object is an instance of class. Object is real world entity which has state, identity
and
behavior.
PROGRAM
import java.util.*;
import java.io.*;
RESULT
Thus the java program for finding whether the given year is leap or not was compiled
and executed successfully.
EX NO:3) LISP
IMPLEMENTATION DATE:
AIM
ALGORITHM
REVIEW QUESTIONS
1. How this() method used with constructors?
this() method within a constructor is used to invoke another constructor in the
same
class.
5. What is Error?
This class describes internal errors, such as out of disk space etc...The user can only
be informed about such errors and so objects of these cannot be thrown
Exceptions.
import java.util.*;
// To implement LISP-like List in Java to perform functions like car, cdr, cons.
class Lisp
{
class Lisp_List2
{
public static void main(String[] args)
{
Lisp a = new Lisp();
Vector v = new Vector(4,1);
Vector v1 = new Vector();
v.addElement("S.R.Tendulkar");
v.addElement("M.S.Dhoni");
v.addElement("V.Sehwag");
v.addElement("S.Raina");
System.out.println(v1);
System.out.println("\n The Contents of this list after CONS..");
v1 = a.cons("Gambhir",v);
v.removeAllElements();
v1.removeAllElements();
v.addElement(3);
v.addElement(0);
v.addElement(2);
v.addElement(5);
System.out.println(v1);
System.out.println("\n The Contents of this list after CONS..");
v1 = a.cons(9,v);
Output
RESULT
Thus the java program for implementing the basic operations of LISP was compiled
and executed successfully.
EX NO:4) POLYMORPHISM - METHOD
OVERLOADING DATE:
AIM
To write a JAVA program to design a Vehicle class hierarchy and a test program to
demonstrate polymorphism concept.
ALGORITHM
1. Define a superclass vehicle with three private integer data members ( speed,color, wheel).
2. Define a function disp() to display the details about vehicle.
3. Define a constructor to initialize the data member cadence, speed and gear.
4. Define a subclass bus which extends superclass vehicle.
5. Overridden disp() method in vehicle class. Additional data about the suspension is
included to the output.
6. Define a subclass train which extends superclass vehicle.
7. There are three classes: bus, train, and car The three subclasses override the disp method
and print unique information.
8. Define a sample class program that creates three vehicle variables. Each variable is
assigned to one of the three vehicle classes. Each variable is then printed.
REVIEW QUESTIONS
1. What is polymorphism?
Polymorphism means the ability to take more than one form. Subclasses of a
class
can define their own unique behaviors and yet share some of the same functionality of
the parent class.
2. What is overloading?
Same method name can be used with different type and number of arguments (in
same
class)
3. What is overriding?
Same method name, similar arguments and same number of arguments can
be defined in super class and sub class. Sub class methods override the super class methods.
5. What is hierarchy?
Ordering of classes (or inheritance)
PROGRAM
import java.util.*;
abstract class Vehicle
{
boolean engstatus=false;
abstract void start();
abstract void moveForward();
abstract void moveBackward();
abstract void applyBrake();
abstract void turnLeft();
abstract void turnRight();
abstract void stop();
}
class Porsche extends Vehicle
{
void truckManufacture()
{
System.out.println("Porsche World Wide Car manufactures ");
}
void gearSystem()
{
System.out.println("\n automatic gearing system.. So don't worry !!");
}
void start()
{
engstatus=true;
System.out.println("\n engine is ON ");
}
void moveForward()
{
if(engstatus==true)
System.out.println("\nCar is moving in forward direction .. Slowly gathering speed ");
else
System.out.println("\n Car is off...Start engine to move");
}
void moveBackward()
{ if(engstatus=true)
System.out.println("\n Car is moving in reverse direction ...");
else
System.out.println("\n Car is off...Start engine to move");
}
void applyBrake()
{
System.out.println("\n Speed is decreasing gradually");
}
void turnLeft()
{
System.out.println("\n Taking a left turn.. Look in the mirror and turn ");
}
void turnRight()
{
System.out.println("\n Taking a right turn.. Look in the mirror and turn ");
}
void stop()
{
engstatus=false;
System.out.println("\n Car is off ");
}
}
class Volvo extends Vehicle
{
void truckManufacture()
{
System.out.println("Volvo Truck Manufactures");
}
void gearSystem()
{
System.out.println("\nManual Gear system...ooops....take care while driving ") ;
}
void start()
{
engstatus=true;
System.out.println("\n engine is ON ");
}
void moveForward()
{
if(engstatus==true)
System.out.println("\n truck is moving in forward direction .. Slowly gathering speed ");
else
System.out.println("\n truck is off...Start engine to move");
}
void moveBackward()
{ if(engstatus=true)
System.out.println("\n truck is moving in reverse direction ...");
else
System.out.println("\n truck is off...Start engine to move");
}
void applyBrake()
{
System.out.println("\n Speed is decreasing gradually");
}
void turnLeft()
{
System.out.println("\n Taking a left turn.. Look in the mirror and turn ");
}
void turnRight()
{
System.out.println("\n Taking a right turn.. Look in the mirror and turn ");
}
void stop()
{
engstatus=false;
System.out.println("\n Truck is off ");
}
}
class Vehicle1
{
public static void main(String[] args)
{
Porsche v1=new Porsche();
v1.truckManufacture();
v1.start();
v1.gearSystem();
v1.moveForward();
v1.applyBrake();
v1.turnLeft();
v1.moveForward();
v1.applyBrake();
v1.turnRight();
v1.moveBackward();
v1.stop();
v1.moveForward();
}
}
RESULT
Thus the java program for design a Vehicle class hierarchy was compiled and
executed
successfully.
NO:5) STACK IMPLEMENTATION USING ARRAY AND LINKED LIST
DATE:
AIM
To write a JAVA program to implement stack using array and linked list.
ALGORITHM
Interface: StackADT
1. Create a StackADT interface with basic stack operations.
Void PUSH(int) & int POP( )
Class: StackArray
1. Create a class StackArray which implements StackAdt using Array.
2. Define the StackArray class with two integer variables(top & size) and one integer array.
3. Initialize the variable top =-1. It indicates that the stack is empty.
4. PUSH method read the element and push it into stack.
Void PUSH(data type
element) IF top==size
THEN
Print Stack Full
ELSE
top++
stack[top]=element
END IF
5. POP method return the data
popped.
Data type POP()
IF top==-1
Print Stack is Empty
ELSE
return stack[top--]
END IF
Class:
StackLinkedlist
1. LinkedList class can be accessed by importing java.util package.
2. Create a class StackLinkedlist which implements StackADT interface.
3. addFirst() method in LinkedList class used to push element in the stack.
4. removeFirst() method in LinkedList class used for deleting an element from stack.
REVIEW QUESTIONS
1. What is Inheritance?
Inheritance is the process by which one object acquires the properties of
another
object. This is important because it supports the concept of hierarchical classification.
5. What is interface?
Interface is a collection of methods declaration and constants that one or more classes of
object will use.
All methods in an interface are implicitly abstract.
All variables are final and static.
Methods should not be declared as static, final, private and protected.
PROGRAM
Stack Interface
package datastruct;
Object pop();
boolean isEmpty();
void makeEmpty();
int size();
Node
Node is the important part of stack implementation. Node holds the information about the element
and connected node.
package datastruct;
Implementation of Stack
package datastruct;
/**
* This example is implementation of Stack using singly Linked List.
* @author jegan
*
*/
public class LinkedStack implements Stack {
private Node top;
private int size;
/**
* Checks weather the Stack is empty or not
*/
@Override
public boolean isEmpty() {
//if value of size is zero then stack is empty.
return (size == 0);
}
/**
* Makes the Stack empty
*/
@Override
public void makeEmpty() {
//make reference of top to null and makes size to zero.
top = null;
size =0;
}
/*
* pops the element in the top of stack.
*/
@Override
public Object pop() {
//if top element is null returns null
if (top == null)
return null; //TO-DO throw new StackEmptyException
RESULT
Thus the java program for implementing stack using array and linked list was compiled
and
executed successfully.
EX NO:6) CURRENCY CONVERSION
DATE:
AIM
To write a JAVA program that randomly generates one number which is stored in a file then
read the dollar value from the file and converts to rupee.
ALGORITHM
1. Random numbers in java can be generated either by using the Random class in
java.util package or by using the random() method in the Math class in java.
2. Using the random() method in Math class
double randomValue =
Math.random();
Using the Random
class
import java.util.Random;
Random random = new Random();
Int
randomValue=random.nextInt();
3. Write the generated random number in a file using FileWriter stream.
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
out.write(randomValue);
out.close();
4. Read the data from the file using FileReader stream.
BufferedReader in = new BufferedReader(new
FileReader("test.txt")); String line = in.readLine();
Int dollar = Integer.parseInt(line);
5. Convert the dollar value into rupee by equation and display it on screen.
REVIEW QUESTIONS
1. Define Stream
Stream produces and consumes information. It is the communication path
between the source and the destination .It is the ordered sequence of data shared by IO
devices.
PROGRAM
SerializationWrite.java
import java.io.*;
import java.util.*;
class Currency implements Serializable
{
protected String currency;
protected int amount;
public Currency(String cur, int amt)
{
this.currency = cur;
this.amount = amt;
}
public String toString()
{
return currency + amount;
}
public String dollarToRupee(int amt)
{
return "Rs" + amt * 45;
}
}
class Rupee extends Currency
{
public Rupee(int amt)
{
super("Rs",amt);
}
}
class Dollar extends Currency
{
public Dollar(int amt)
{
super("$",amt);
}
}
public class SerializationWrite
{
public static void main(String args[])
{
Random r = new Random();
try
{
Currency currency;
FileOutputStream fos = new FileOutputStream("serial.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("Writing to file using Object Serialization:");
for(int i=1;i<=25;i++)
{
Object[] obj = { new Rupee(r.nextInt(5000)),new Dollar(r.nextInt(5000)) };
currency = (Currency)obj[r.nextInt(2)]; // RANDOM Objects for Rs and $
System.out.println(currency);
oos.writeObject(currency);
oos.flush();
}
oos.close();
}
catch(Exception e)
{
System.out.println("Exception during Serialization: " + e);
}
}
}
SerializationRead.java
import java.io.*;
import java.util.*;
public class SerializationRead
{
public static void main(String args[])
{
try
{
Currency obj;
FileInputStream fis = new FileInputStream("serial.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println("Reading from file using Object Serialization:");
for(int i=1;i<=25;i++)
{
obj = (Currency)ois.readObject();
if((obj.currency).equals("$"))
System.out.println(obj + " = " + obj.dollarToRupee(obj.amount));
else
System.out.println(obj + " = " + obj);
}
ois.close();
}
catch(Exception e)
{
System.out.println("Exception during deserialization." + e);
}
}
}
Output
vivek@ubuntu:~/Desktop$ javac SerializationWrite.java
vivek@ubuntu:~/Desktop$ java SerializationWrite
Writing to file using Object Serialization:
$4645
Rs105
$2497
$892
Rs1053
Rs1270
$1991
Rs4923
Rs4443
Rs3537
Rs2914
$53
$561
$4692
Rs860
$2764
Rs752
$1629
$2880
Rs2358
Rs3561
$3796
Rs341
Rs2010
Rs427
vivek@ubuntu:~/Desktop$ javac SerializationRead.java
vivek@ubuntu:~/Desktop$ java SerializationRead
Reading from file using Object Serialization:
$4645 = Rs209025
Rs105 = Rs105
$2497 = Rs112365
$892 = Rs40140
Rs1053 = Rs1053
Rs1270 = Rs1270
$1991 = Rs89595
Rs4923 = Rs4923
Rs4443 = Rs4443
Rs3537 = Rs3537
Rs2914 = Rs2914
$53 = Rs2385
$561 = Rs25245
$4692 = Rs211140
Rs860 = Rs860
$2764 = Rs124380
Rs752 = Rs752
$1629 = Rs73305
$2880 = Rs129600
Rs2358 = Rs2358
Rs3561 = Rs3561
$3796 = Rs170820
Rs341 = Rs341
Rs2010 = Rs2010
Rs427 = Rs427
RESULT
Thus the java program for currency conversion was compiled and executed successfully.
EX NO:7) MUTLITHREADING
DATE:
AIM
To write a JAVA program to print all numbers below 100,000 that are both prime
and
Fibonacci number.
ALGORITHM
For creating a thread a class has to extend the Thread Class. For creating a thread by
this procedure you have to follow these steps:
Like creation of a single thread, create more than one thread (multithreads) in a program
using class Thread or implementing interface Runnable.
REVIEW QUESTIONS
1. What is thread?
Thread is similar to a program that has single flow of control. Each thread
has
separate path for execution.
2. What is multithreading?
Simultaneous execution of threads is called
multithreading.
RESULT
Thus the java program for creating multithread was compiled and executed successfully.
EX NO:8) SCIENTIFIC CALCULATOR
DATE:
AIM
ALGORITHM
1. Import applet, awt and awt.event packages.
2. Create a class calculator which extends Applet and implements ActionListener.
3. Create object for TextFiled, List, Label and Button classes. Add all these objects to
the window using add(obj) method.
4. Use addActionerListener(obj) method to receive action event notification from
component.
When the button is pressed the generated event is passed to every EventListener objects
that receives such types of events using the addActionListener() method of the object.
5. Implement the ActionListener interface to process button events
using actionPerformed(ActionEvent obj) method.
6. Align the buttons in container by using Grid Layout.The format of grid layout
constructor is public GridLayout(int numRows, int NumColumns, int horz, int vert)
7. Set the layout for the window using setLayout(gridobj(row,column)) method.
REVIEW QUESTIONS
1. What is an applet?
Applet is a dynamic and interactive program that runs inside a web page
displayed by a java capable browser.
4. What is a layout manager and what are different types of layout managers available
in java AWT?
A layout manager is an object that is used to organize components in a
container. The different layouts are available are
FlowLayout
BorderLayout
CardLayout
GridLayout and GridBagLayout.
// Initial Declarations
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
// Creating a class named Calculator
class Calculator
{
// Components that are required to create the Calculator
JFrame frame = new JFrame();
// Creating the Menu Bar
JMenuBar menubar = new JMenuBar();
//---> Creating the "Calculator-->Exit" Menu
JMenu firstmenu = new JMenu("Calculator");
JMenuItem exitmenu = new JMenuItem("Exit");
// Creating The TextArea that gets the value
JTextField editor = new JTextField();
JRadioButton degree = new JRadioButton("Degree");
JRadioButton radians = new JRadioButton("Radians");
String[] buttons = {"BKSP","CLR","sin","cos","tan","7","8","9","/","+/-
","4","5","6","X","x^2","1","2","3","-","1/x","0",".","=","+","sqrt"};
JButton[] jbuttons = new JButton[26];
double buf=0,result;
boolean opclicked=false,firsttime=true;
String last_op;
// Creating a Constructor to Initialize the Calculator Window
public Calculator()
{
frame.setSize(372,270);
frame.setTitle("Calculator - By G.Vivek Venkatesh.");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
ButtonHandler bhandler = new ButtonHandler();
menubar.add(firstmenu);
firstmenu.add(exitmenu);
exitmenu.setActionCommand("mExit");
exitmenu.addActionListener(bhandler);
editor.setPreferredSize(new Dimension(20,50));
Container buttoncontainer = new Container();
buttoncontainer.setLayout(new GridLayout(5,5));
for(int i=0;i
{
jbuttons[i] = new JButton(buttons[i]);
jbuttons[i].setActionCommand(buttons[i]);
jbuttons[i].addActionListener(bhandler);
buttoncontainer.add(jbuttons[i]);
}
JPanel degrad = new JPanel();
degrad.setLayout(new FlowLayout());
ButtonGroup bg1 = new ButtonGroup();
bg1.add(degree);
bg1.add(radians);
degrad.add(degree);
radians.setSelected(true);
degrad.add(radians);
frame.setJMenuBar(menubar);
frame.add(editor,BorderLayout.NORTH);
frame.add(degrad,BorderLayout.CENTER);
frame.add(buttoncontainer,BorderLayout.SOUTH);
frame.setVisible(true);
}
// Class that handles the Events (that implements ActionListener)
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if(action == "0" || action=="1" || action=="2" || action=="3" || action=="4" || action=="5" ||
action=="6" || action=="7" || action=="8" || action=="9" || action==".")
{
if(opclicked == false)
editor.setText(editor.getText() + action);
else
{
editor.setText(action);
opclicked = false;
}
}
if(action == "CLR")
{
editor.setText("");
buf=0;
result=0;
opclicked=false;
firsttime=true;
last_op=null;
}
//Addition
if(action=="+")
{
firsttime = false;
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-")
{
buf = buf + Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "+";
opclicked=true;
}
else
{
opclicked=true;
last_op = "+";
}
}
// Subtraction
if(action=="-")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
opclicked=true;
last_op = "-";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-")
{
buf = buf - Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "-";
opclicked=true;
}
else
{
opclicked=true;
last_op = "-";
}
}
}
//Multiplication
if(action=="X")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
opclicked = true;
last_op = "X";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-")
{
buf = buf * Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "X";
opclicked=true;
}
else
{
opclicked=true;
last_op = "X";
}
}
}
//Division
if(action=="/")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
opclicked=true;
last_op = "/";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" && last_op!="x^2" && last_op!="+/-")
{
buf = buf / Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "/";
opclicked=true;
}
else
{
opclicked=true;
last_op = "/";
}
}
}
// Equal to
if(action=="=")
{
result = buf;
if(last_op=="+")
{
result = buf + Double.parseDouble(editor.getText());
buf = result;
}
if(last_op=="-")
{
result = buf - Double.parseDouble(editor.getText());
buf = result;
}
if(last_op=="X")
{
result = buf * Double.parseDouble(editor.getText());
buf = result;
}
if(last_op=="/")
{
try
{
result = buf / Double.parseDouble(editor.getText());
}
catch(Exception ex)
{
editor.setText("Math Error " + ex.toString());
}
buf = result;
}
editor.setText(Double.toString(result));
last_op = "=";
}
// Sqrt
if(action=="sqrt")
{
if(firsttime==false)
{
buf = Math.sqrt(buf);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sqrt";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sqrt(buf);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sqrt";
}
}
}
// Reciprocal
if(action=="1/x")
{
if(firsttime==false)
{
buf = 1/ buf;
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "1/x";
}
else
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = 1 / buf;
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "1/x";
}
}
}
// Square
if(action=="x^2")
{
if(firsttime==false)
{
buf = buf * buf;
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "x^2";
}
else
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = buf * buf;
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "x^2";
}
}
}
// Negation +/-
if(action=="+/-")
{
if(firsttime==false)
{
buf = -(buf);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "+/-";
}
else
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = -(buf);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "+/-";
}
}
}
// Exit
if(action=="mExit")
{
frame.dispose();
System.exit(0);
}
if(action=="mCut")
editor.cut();
if(action=="mCopy")
editor.copy();
if(action=="mPaste")
editor.paste();
if(action=="sin")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sin";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sin";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.sin(rad);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sin";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.sin(rad);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sin";
}
}
}
}// end of sin
if(action=="cos")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.cos(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "cos";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "cos";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.cos(rad);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "cos";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.cos(rad);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "cos";
}
}
}
}// end of cos
if(action=="tan")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.tan(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "tan";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.tan(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "tan";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.tan(rad);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "tan";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.tan(rad);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "tan";
}
}
}
}// end of tan
}
}
}
RESULT
Thus the java program for design a scientific calculator was compiled and
executed
successfully.
EX NO:9) OPAC SYSTEM FOR
LIBRARY DATE:
AIM
To develop a simple OPAC system for library using event driven programming paradigm
of
JAVA and it is connected with backend database using JDBC connection.
ALGORITHM
1. Create a database table Books with following fields
Field Name Data Type
Title String
Author String
Edition Int
ISBN String
2. Define a class Library that must have the following methods for accessing the
information
about the books available in
library. a. addBook( )
b. deleteBook( )
c. viewBooks( )
3. Design the user interface screen with necessary text boxes and buttons. This page
is formatted using grid layout.
Method: addBook( )
This method takes the book title, author name,edition and ISBN as input parameters
and store them in Books table.
1. Establish connection with database
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:DSN”,””,””);
2. Add the details in Books table.
PreparedStatement ps=con.prepareStatement(“insert into Books
values(?,?,?,?)”); Ps.setString(1,title);
Ps.setString(2,author)
; Ps.setInt(3,edition);
Ps.setString(4,ISBN);
3. Execute the statement.
ps.executeUpdate()
;
4. Close the connection.
Method :deleteBook()
1. Establish connection with database
2. Delete the details from Books table.
PreparedStatement ps=con.prepareStatement(“delete from Books where
author=?”); Ps.setString(1,author);
3. Execute the statement.
ps.executeQuery()
;
4. Close the connection.
Method :viewBook()
1. Establish connection with database
2. read the details in Books table.
PreparedStatement ps=con.prepareStatement(“select * from Books where
title=?”); Ps.setString(1,title);
3. Execute the statement.
ps.executeQuery()
;
4. Close the connection.
REVIEW QUESTIONS
4. What are the steps involved for making a connection with a database or how do
you connect to a database?
1) Loading the driver:
Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”);
When the driver is loaded, it registers itself with the java. sql. DriverManager
class as an available database driver.
2) Making a connection with database:
Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”,
“password”);
3) Executing SQL statements :
Statement stmt = con. createStatement();
ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”);
4) Process the results : ResultSet returns one row at a time.
Next() method of ResultSet object can be called to move to the next row.
The getString() and getObject() methods are used for retrieving column values.
5. Define ODBC.
ODBC is a standard for accessing different database systems. There are interfaces
for
Visual Basic, Visual C++, SQL and the ODBC driver pack contains drivers for the
Access, Paradox, dBase, Text, Excel and Btrieve databases
PROGRAM
Develop a simple OPAC system for library using even-driven and concurrent programming
paradigms of Java. Use JDBC to connect to a back-end database.
Procedure
i. AuthorName – Text
ii. ISBN – Text
iii. BookName - Text
iv. Price - Number
v. Publisher – Text
Now your database file gets added to the System DSN. It should look like below,
Now execute the following code “Library.java”.
Library.java
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Library implements ActionListener
{
JRadioButton rbauthor = new JRadioButton("Search by Author name");
JRadioButton rbbook = new JRadioButton("Search by Book name");
JTextField textfld = new JTextField(30);
JLabel label = new JLabel("Enter Search Key");
JButton searchbutton = new JButton("Search");
JFrame frame = new JFrame();
JTable table;
DefaultTableModel model;
String query = "select * from Library";
public Library()
{
frame.setTitle("Online Public Access Catalog");
frame.setSize(500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
p1.setLayout(new FlowLayout());
p1.add(label);
p1.add(textfld);
ButtonGroup bg = new ButtonGroup();
bg.add(rbauthor);
bg.add(rbbook);
p2.setLayout(new FlowLayout());
p2.add(rbauthor);
p2.add(rbbook);
p2.add(searchbutton);
searchbutton.addActionListener(this);
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 s)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Library","","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(s);
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
model = new DefaultTableModel(1,cols);
table = new JTable(model);
String[] tabledata = new String[cols];
int i=0;
while(i0)
model.removeRow(0);
frame.remove(table);
addTable(query);
}
public static void main(String[] args)
{
new Library();
}
}
RESULT
Thus the java program for develop a simple OPAC system for library was compiled
and
executed successfully.
EX NO:10) CHATTING
DATE:
AIM
To implement a simple chat application using JAVA.
ALGORITH
M Server
1. Import io and net packages.
2. Using InputStreamReader(System.in) class read the contents from keyboard and pass it to
BufferedReader class.
3. Create a server socket using DatagramSocket(port no) class.
4. Use DatagramPacket() class to create a packet.
5. To send and receive the datagram packets, use send(packetobj) and receive(packetobj).
Client
1. Import io and net packages.
2. Using InputStreamReader(System.in) class read the contents from keyboard and pass it to
BufferedReader class.
3. Create a client socket using DatagramSocket(port no) class.
4. Use DatagramPacket() class to create a packet.
5. To send and receive the datagram packets, use send(packetobj) and receive(packetobj).
REVIEW QUESTIONS
1. Define socket.
The socket is a software abstraction used to represent the terminals of a connection
between
two machines or processes. (Or) it is an object through which application sends or
receives packets of data across network.
Server Code
import java.net.*;
import java.io.*;
ds=new DatagramSocket(serverPort);
System.out.println(“Server is waiting..”);
InetAddress in=InetAddress.getByName(“localhost”);
int cho;
cho=Integer.parseInt(br.readLine());
switch(cho)
case 1:
while(true)
String s=dfs.readLine();
if(s==null||s.equals(“ends”))
break;
buff=s.getBytes();
ds.send(new DatagramPacket(buff,s.length(),in,clientPort));
break;
case 2:
while(true)
ds.receive(p);
System.out.println(s1);
}
Client Code
import java.net.*;
import java.io.*;
class client10
ds=new DatagramSocket(clientPort);
InetAddress in=InetAddress.getLocalHost();
int cho;
cho=Integer.parseInt(br.readLine());
switch(cho)
case 1:
while(true)
ds.receive(p);
System.out.println(s1);
case 2:
while(true)
String s=br.readLine();
if(s==null||s.equals(“ends”))
break;
buff=s.getBytes();
ds.send(new DatagramPacket(buff,s.length(),in,serverPort));
break;
RESULT
Thus the java program for developing chat application was compiled and
executed
successfully.
EX NO:11) DATE CLASS IMPLEMENTATION
DATE:
AIM
1. Import
sun.util.calendar.CalendarDate,sun.util.calendar,java.text.DateFormat and
sun.util.calendar.BaseCalendar packages.
2. Create an instance to the class BaseCalendar in util package.
3. Get the Date and time using getGregorianCalendar() method.
BaseCalendar gcal =
CalendarSystem.getGregorianCalendar();
4. currentTimeMillis() method is used to return the current time in milliseconds.
5. Get year using getYear() method in CalenderSystem class and display it on screen.
REVIEW QUESTIONS
PROGRAM
import java.util.*;
public CDate(int day, int month, int year) // constructor with parameters
{
setDate(day, month, year);
}
System.out.println("Please enter today's date (month, day, and year separated by spaces):");
inputLine = console.nextLine();
}
}
RESULT
Thus the java program for implementing Date class was compiled and
executed
successfully.