CS3381 - OOPS LAB MANUAL (1) Ssss
CS3381 - OOPS LAB MANUAL (1) Ssss
ADDITIONAL EXPERIMENTS
12 DECISION MAKING STATEMENTS
13 IMPLEMENTING STRING FUNCTIONS
14 DESIGN APPLET
15 IMPLEMENTING GRAPHIC CLASS METHODS
Ex.No.1(a) LINEAR SEARCH PROGRAM
Aim
To develop a Java application to search a key element from multiple elements using Linear
Search
Algorithm:
Step 3: If key element is found, return the index position of the array element
PROGRAM
OUTPUT
Ex.No.1(b) BINARY SEARCH PROGRAM
Aim
To develop a Java application to search a key element from multiple elements using Binary
search
Algorithm:
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate
the function.
Step 5 - If both are not matched, then check whether the search element is smaller or
larger than the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and
5 for the left sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5
for the right sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until
sublist contains only one element.
Step 9 - If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.
PROGRAM
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
OUTPUT:
Aim
Algorithm
Step 1 – Initialize minimum value(min_idx) to location 0
Step 2 − Traverse the array to find the minimum element in the array
Step 3 – While traversing if any element smaller than min_idx is found then swap both the
values.
Step 4 − Then, increment min_idx to point to next element
Step 5 – Repeat until array is sorted
PROGRAM
OUTPUT
Ex.No.1(d) INSERTION SORT PROGRAM
Aim
Algorithm
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
PROGRAM
OUTPUT
Aim
Algorithm:
class Stack {
int top;
boolean isEmpty()
Stack()
top = -1;
boolean push(int x)
System.out.println("Stack Overflow");
return false;
else {
a[++top] = x;
return true;
int pop()
if (top < 0) {
System.out.println("Stack Underflow");
return 0;
}
else {
int x = a[top--];
return x;
void print(){
for(int i = top;i>-1;i--){
// Driver code
class Main {
s.push(10);
s.push(20);
s.push(30);
s.print();
Output:
Aim
Algorithm:
PROGRAM
// implementation of queue
class Queue {
int capacity;
int array[];
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
if (isFull(this))
return;
this.size = this.size + 1;
int dequeue()
if (isEmpty(this))
return Integer.MIN_VALUE;
this.size = this.size - 1;
return item;
int front()
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.front];
}
int rear()
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.rear];
// Driver class
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
Output
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from queue
Front item is 20
Rear item is 40
To develop a java application to generate pay slip for different category of employees using
the concept of inheritance.
ALGORITHM:
1. Create the class employee with name, Empid, address, mailid, mobileno as members.
4. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as
0.1% of BP.
7. Create the objects for the inherited classes and invoke the necessary methods to display the
Payslip
PROGRAM
class employee
int empid;
long mobile;
void getdata()
name = get.nextLine();
mailid = get.nextLine();
address = get.nextLine();
empid = get.nextInt();
mobile = get.nextLong();
}
void display()
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
bp = get.nextDouble();
void calculateprog()
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
bp = get.nextDouble();
void calculateasst()
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("NET PAY:Rs"+net);
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
bp = get.nextDouble();
void calculateassociate()
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
bp = get.nextDouble();
void calculateprofessor()
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class salary
int choice,cont;
do
System.out.println("PAYROLL PROGRAM");
choice=c.nextInt();
switch(choice)
case 1:
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
case 2:
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
case 3:
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
case 4:
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
cont=c.nextInt();
}while(cont==1);
OUTPUT:
RESULT:
Thus the java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.
AIM:
To write a java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class.
PROCEDURE:
1. Create an abstract class named shape that contains two integers and an empty method
named printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the classes
extends the class Shape.
3.Each of the inherited class from shape class should provide the implementation for the
method printarea().
4.Get the input and calculate the area of rectangle,circle and triangle .
5. In the shapeclass , create the objects for the three inherited classes and invoke the methods
and display the area values of the different shapes.
PROGRAM:
import java.util.*;
float area;
area= x * y;
float area;
area= (x * y) / 2.0f;
float area;
area=(22 * x * x) / 7.0f;
}
}
int choice;
choice=sc.nextInt();
switch(choice) {
case 1:
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2:
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3:
c.x = sc.nextInt();
c.printArea();
break;
OUTPUT:
RESULT:
Thus a java program for calculate the area of rectangle,circle and triangle was implemented
and executed successfully.
AIM:
To write a java program to calculate the area of rectangle and circle using the concept of
interface.
PROCEDURE:
1. Create an abstract class named shape that contains two integers and an empty method
named printarea().
2. Provide two classes named rectangleand circle such that each one of the classes extends the
class Shape.
3. Each of the inherited class from shape class should provide the implementation for the
method printarea().
4. Get the input and calculate the area of rectangle and circle.
5. In the shapeclass , create the objects for the two inherited classes and invoke the methods
and display the area values of the different shapes.
PROGRAM
interface Shape
void input();
void area();
int r = 0;
double pi = 3.14, ar = 0;
@Override
r = 5;
@Override
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
}
class Rectangle extends Circle
int l = 0, b = 0;
double ar;
super.input();
l = 6;
b = 4;
super.area();
ar = l * b;
System.out.println("Area of rectangle:"+ar);
obj.input();
obj.area();
}
}
Output:
$ javac Demo.java
$ java Demo
Area of circle:78.5
Area of rectangle:24.0
RESULT:
Thus a java program for calculate the area was implemented and executed successfully.
HANDLING
AIM:
ALGORITHM:
5.Using the exception handling mechanism , the thrown exception is handled by the catch
construct.
6.After the exception is handled , the string “invalid amount “ will be displayed.
7.If the amount is greater than 0 , the message “Amount Deposited “ will be displayed
PROGRAM:
import java.util.Scanner;
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
return msg;
System.out.print("Enter Amount:");
int a=s.nextInt();
try
if(a<0)
System.out.println("Amount Deposited");
catch(NegativeAmtException e)
System.out.println(e);
OUTPUT:
(b) PROGRAM:
Algorithm:
PROGRAM
String str1;
MyException(String str2)
str1=str2;
class example
{
public static void main(String args[])
try
catch(MyException exp)
System.out.println("Catch Block") ;
System.out.println(exp) ;
}}
OUTPUT:
RESULT:
Thus a java program to implement user defined exception handling has been implemented
and executed successfully.
Ex.No.7 PROGRAM TO IMPLEMENT MULTITHREADED APPLICATION
AIM:
To write a java program that implements a multi-threaded application .
ALGORITHM
1.Create a class even which implements first thread that computes .the square of the number .
2. run() method implements the code to be executed when thread gets executed.
3.Create a class odd which implements second thread that computes the cube of the number.
4.Create a third thread that generates random number.If the random number is even , it
displays
the square of the number.If the random number generated is odd , it displays the cube of the
given number .
5.The Multithreading is performed and the task switched between multiple threads.
6.The sleep () method makes the thread to suspend for the specified time.
PROGRAM
MultiThreadRandOddEven.java
import java.util.*;
public int a;
public EvenNum(int a) {
this.a = a;
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
public int a;
public OddNum(int a) {
this.a = a;
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
int n = 0;
try {
n = rand.nextInt(20);
if (n % 2 == 0) {
thread1.start();
else {
thread2.start();
Thread.sleep(1000);
System.out.println("------------------------------------");
System.out.println(ex.getMessage());
// Driver class
public class MultiThreadRandOddEven {
rand_num.start();
Output:
RESULT:
Aim
Algorithm:
PROGRAM
import java.io.File;
// Importing the IOException class for handling errors
import java.io.IOException;
class CreateFile {
public static void main(String args[]) {
try {
// Creating an object of a file
File f0 = new File("D:File1.txt");
if (f0.createNewFile()) {
System.out.println("File " + f0.getName() + " is created successfully.");
} else {
System.out.println("File is already exist in the directory.");
}
} catch (IOException exception) {
System.out.println("An unexpected error is occurred.");
exception.printStackTrace();
}
}
}
OUTPUT
Aim:
To read and display a file’s properties.
Procedure:
Step 1: Start the program.
Step 2: Import scanner and file classes.
Step 3: Use scanner method to get file name from user.
Step 4: Create a file object.
Step 5: Call the respective methods to display file properties like getName(), getPath() etc.
Step 6: Stop the program
Program:
import java.util.Scanner;
import java.io.File;
class fileDemo
String s = input.nextLine();
File f1=new File(s);
System.out.println("-------------------------");
Output:
C:\ >javac fileDemo.java
C:\ >java fileDemo
Enter the file name:
fileDemo.java
-------------------------
File Name: fileDemo.java
Path: fileDemo.java
Abs Path: D:\ Ex 08\fileDemo.java
This file: Exists
File: true
Directory: false
Readable: true
Writable: true
Absolute: false
File Size: 895bytes
Is Hidden: false
Ex.No.8(c) Write Content into File
Aim
Algorithm
PROGRAM
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
try {
if (objFile.exists() == false) {
if (objFile.createNewFile()) {
} else {
System.exit(0);
}
}
String text;
text = SC.nextLine();
//object of FileOutputStream
fileOut.write(text.getBytes());
fileOut.flush();
fileOut.close();
System.out.println("File saved.");
OUTPUT
Ex.No.8(d) Read Content from File
Aim
Algorithm
Step3: FileInputStream.read() method which returns an integer value and will read values
until -1 is not found
PROGRAM
import java.io.File;
import java.io.FileInputStream;
try {
if (objFile.exists() == false) {
System.exit(0);
String text;
int val;
//object of FileOutputStream
System.out.print((char) val);
}
System.out.println();
fileIn.close();
OUTPUT
AIM:
To write a java program to find the maximum value from the given type of elements using a
generic function.
ALGORITHM:
3.Create the objects of the class to hold integer,character and double values.
4.Create the method to compare the values and find the maximum value stored in the array.
5.Invoke the method with integer, character or double values . The output will be displayed
based on the data type passed to the method.
PROGRAM
T[] vals;
MyClass(T[] o)
vals = o;
public T min()
T v = vals[0];
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
public T max()
T v = vals[0];
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
class gendemo
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
OUTPUT
Aim:
PROGRAM
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.ToggleButton;
import javafx.stage.Stage;
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(locationLabel, 0, 6);
gridPane.add(locationchoiceBox, 1, 6);
gridPane.add(buttonRegister, 2, 8);
//Styling nodes
buttonRegister.setStyle(
"-fx-background-color: darkslateblue; -fx-textfill: white;");
OUTPUT
Ex.No.10(b) DEVELOP APPLICATIONS USING JAVAFX LAYOUTS
Aim
ALGORITHM
Create a Java class and inherit the Application class of the package javafx.application and
implement the start() method
Create a Scene by instantiating the class named Scene which belongs to the package
javafx.scene.
You can set the title to the stage using the setTitle() method of the Stage class. The
primaryStage is a Stage object which is passed to the start method of the scene class, as a
parameter.
You can add a Scene object to the stage using the method setScene() of the class named
Stage.
Display the contents of the scene using the method named show() of the Stage class
Launch the JavaFX application by calling the static method launch() of the Application class
from the main method
PROGRAM
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.geometry.Insets;
@Override
public void start(Stage primaryStage) {
pane.setHgap(5);
pane.setVgap(5);
tfMi.setPrefColumnCount(1);
new TextField());
primaryStage.setTitle("ShowFlowPane");
launch(args);
OUTPUT
Ex.No.10(c) DEVELOP APPLICATIONS USING JAVAFX MENUS
Aim
Algorithm
Step 2: JavaFX provides five classes that implement menus: MenuBar, Menu, MenuItem,
CheckMenuItem, and RadioButtonMenuItem.
Step 4: A menu consists of menu items that the user can select (or toggle on or off).
Step 6: Menu items can be associated with nodes and keyboard accelerators.
PROGRAM
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.geometry.Pos;
public class MenuDemo extends Application {
private TextField tfNumber1 = new TextField();
private TextField tfNumber2 = new TextField();
private TextField tfResult = new TextField();
@Override
public void start(Stage primaryStage) {
MenuBar menuBar = new MenuBar();
Menu menuOperation = new Menu("Operation");
Menu menuExit = new Menu("Exit");
menuBar.getMenus().addAll(menuOperation, menuExit);
MenuItem menuItemAdd = new MenuItem("Add");
MenuItem menuItemSubtract = new MenuItem("Subtract");
MenuItem menuItemMultiply = new MenuItem("Multiply");
MenuItem menuItemDivide = new MenuItem("Divide");
menuOperation.getItems().addAll(menuItemAdd, menuItemSubtract,
menuItemMultiply, menuItemDivide);
MenuItem menuItemClose = new MenuItem("Close");
menuExit.getItems().add(menuItemClose);
menuItemAdd.setAccelerator(
KeyCombination.keyCombination("Ctrl+A"));
menuItemSubtract.setAccelerator(
KeyCombination.keyCombination("Ctrl+S"));
menuItemMultiply.setAccelerator(
KeyCombination.keyCombination("Ctrl+M"));
menuItemDivide.setAccelerator(
KeyCombination.keyCombination("Ctrl+D"));
HBox hBox1 = new HBox(5);
tfNumber1.setPrefColumnCount(2);
tfNumber2.setPrefColumnCount(2);
tfResult.setPrefColumnCount(2);
hBox1.getChildren().addAll(new Label("Number 1:"), tfNumber1,
new Label("Number 2:"), tfNumber2, new Label("Result:"),
tfResult);
hBox1.setAlignment(Pos.CENTER);
HBox hBox2 = new HBox(5);
Button btAdd = new Button("Add");
Button btSubtract = new Button("Subtract");
Button btMultiply = new Button("Multiply");
Button btDivide = new Button("Divide");
hBox2.getChildren().addAll(btAdd, btSubtract, btMultiply, btDivide);
hBox2.setAlignment(Pos.CENTER);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(menuBar, hBox1, hBox2);
Scene scene = new Scene(vBox, 300, 250);
primaryStage.setTitle("MenuDemo"); // Set the window title
primaryStage.setScene(scene); // Place the scene in the window
primaryStage.show(); // Display the window
// Handle menu actions
menuItemAdd.setOnAction(e -> perform('+'));
menuItemSubtract.setOnAction(e -> perform('-'));
menuItemMultiply.setOnAction(e -> perform('*'));
menuItemDivide.setOnAction(e -> perform('/'));
menuItemClose.setOnAction(e -> System.exit(0));
// Handle button actions
btAdd.setOnAction(e -> perform('+'));
btSubtract.setOnAction(e -> perform('-'));
btMultiply.setOnAction(e -> perform('*'));
btDivide.setOnAction(e -> perform('/'));
}
private void perform(char operator) {
double number1 = Double.parseDouble(tfNumber1.getText());
double number2 = Double.parseDouble(tfNumber2.getText());
double result = 0;
switch (operator) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case '*': result = number1 * number2; break;
case '/': result = number1 / number2; break;
}
tfResult.setText(result + "");
};
public static void main(String[] args) {
launch(args);
}
}
OUTPUT
Aim:
To develop scientific calculator application using AWT and Swing.
ALGORITHM
PROGRAM
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener {
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;
ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc = new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
mp = new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
mm = new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero = new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plus = new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
min = new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mul = new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
addSub = new JButton("+/-");
buttonpanel.add(addSub);
addSub.addActionListener(this);
dot = new JButton(".");
buttonpanel.add(dot);
dot.addActionListener(this);
eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
rec = new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);
sin = new JButton("SIN");
buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);
clr = new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if (s.equals("1")) {
if (z == 0) {
tfield.setText(tfield.getText() + "1");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2")) {
if (z == 0) {
tfield.setText(tfield.getText() + "2");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3")) {
if (z == 0) {
tfield.setText(tfield.getText() + "3");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4")) {
if (z == 0) {
tfield.setText(tfield.getText() + "4");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5")) {
if (z == 0) {
tfield.setText(tfield.getText() + "5");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6")) {
if (z == 0) {
tfield.setText(tfield.getText() + "6");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9")) {
if (z == 0) {
tfield.setText(tfield.getText() + "9");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0")) {
if (z == 0) {
tfield.setText(tfield.getText() + "0");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals(".")) {
if (y == 0) {
tfield.setText(tfield.getText() + ".");
y = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals("+")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '+';
} else {
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '-';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '/';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '*';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText()); //string to double
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC")) {
m1 = 0;
tfield.setText("");
}
if (s.equals("MR")) {
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("=")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
temp1 = Double.parseDouble(tfield.getText());
switch (ch) {
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a = fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}
double fact(double x) {
int er = 0;
if (x < 0) {
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[]) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}
OUTPUT
Aim:
Program to find largest of three numbers
PROGRAM
import java.util.Scanner;
public class ifdemo
{
public static void main(String args[])
{
int num1, num2, num3;
System.out.println("Enter three integers: ");
Scanner in = new Scanner(System.in);
num1=in.nextInt();
num2=in.nextInt();
num3=in.nextInt();
if (num1 > num2 && num1 > num3)
System.out.println("The largest number is: "+num1);
else if (num2 > num1 && num2 > num3)
System.out.println("The largest number is: "+num2);
else if (num3 > num1 && num3 > num2)
System.out.println("The largest number is: "+num3);
else
System.out.println("The numbers are same.");
}
}
OUTPUT
AIM:
To create a JAVA program to implement the string operation.
ALGORITHM:
STEP 1: Start the process.
STEP 2: Create a class StringExample.
STEP 3: Declare the string variables S1, X.
STEP 4: Concentrate the string and integer values and store it in string S2.
STEP 5: Declare S3 string and assign it the substring () function and also declare string S4
and S5. STEP 6: Display the string S1, S2, S3, S4, S5 using system.out.println ().
STEP 7: Declare the integer variable x and y string variables.
STEP 8: Display the string S6, S7 and S8.
STEP 9: Stop the process.
PROGRAM
OUTPUT
Aim:
Program to demonstrate use of Graphics Programming to display different shapes and msg
using Applet
PROGRAM
GraphicsDemo.java
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
GraphicsDemo.html
<html>
<head>
</head>
<body>
/*<applet code="GraphicsDemo.class" height=500 width=300></applet>*/
</body>
</html>
OUTPUT
PROGRAM
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class Javaapp extends Applet {
public void paint(Graphics g) {
int a=150,b=150,c=100,d=100;
g.setColor(Color.red);
for(int i=0;i<15;i++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex){}
g.drawOval(a,b,c,d);
a-=10;
b-=10;
c+=8;
d+=8;
}
}
}
<html>
<applet code="Javaapp" height=400 width=400>
</applet>
</html>
OUTPUT