OOPS Record Manual.
OOPS Record Manual.
PAGE STAFF
EX.NO. DATE EXPERIMENT NAME MARKS
NO. SIGN
1(A) LINEAR SEARCH PROGRAM 2
1(B) BINARY SEARCH PROGRAM 4
1(C) SELECTION SORT PROGRAM 6
1(D) INSERTION SORT PROGRAM 8
STACK ADT USING CLASSES
2(A) 10
AND OBJECTS
QUEUE ADT USING CLASSES
2(B) 13
AND OBJECTS
PROGRAM TO GENERATE
3 18
PAYSLIP
PROGRAM TO CALCULATE
4 27
AREA USING ABSTRACT CLASS
PROGRAM TO CALCULATE
5 31
AREA USING INTERFACE
PROGRAM TO IMPLEMENT
6 USER DEFINED EXCEPTION 34
HANDLING
PROGRAM TO IMPLEMENT
7 MULTITHREADED 38
APPLICATION
8(A) FILE CREATION 41
8(B) DISPLAYING FILE PROPERTIES 42
8(C) WRITE CONTENT FROM FILE 44
8(D) READ CONTENT FROM FILE 47
9 GENERIC PROGRAMING 49
DEVELOP APPLICATION USING
10(A) 52
JAVAFX CONTROLS
DEVELOP APPLICATION USING
10(B) 57
JAVAFX LAYOUTS
DEVELOP APPLICATION USING
10(C) 60
JAVAFX MENUS
11 SCIENTIFIC CALCULATOR 63
ADDITIONAL EXPERIMENTS
DECISION MAKING
12 73
STATEMENTS
IMPLEMENTING STRING
13 74
FUNCTION
14 DESIGN APPLET 76
IMPLEMENTING GRAPHIC
15 78
CLASS METHODS
EX.NO.1(A) LINEAR SEARCH PROGRAM
DATE:
AIM:
To develop a Java application to search a key element from multiple elements using
Linear Search
ALGORITHM:
Step 1: Traverse the array
Step 3: If key element is found, return the index position of the array element
PROGRAM:
import java.io.*;
public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
2
OUTPUT:
RESULT:
Thus the Java application to search a key element from multiple elements using Linear
Search was implemented and executed successfully.
3
EX.NO.1(B)
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:
import java.io.*;
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 ){
4
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:
RESULT:
Thus the Java application to search a key element from multiple elements using Binary
search is implemented and executed successfully.
5
EX.NO.1(C) SELECTION SORT PROGRAM
DATE:
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:
import java.io.*;
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
OUTPUT:
RESULT:
Thus the Java application to sort array elements using selection sort was implemented
and executed successfully.
7
EX.NO.1(D) INSERTION SORT PROGRAM
DATE:
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:
import java.io.*;
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
OUTPUT:
RESULT:
Thus the Java application to sort array elements using insertion sort is implemented and
executed successfully.
9
EX.NO.2(A) STACK ADT USING CLASSES AND OBJECTS
DATE:
AIM:
ALGORITHM:
PROGRAM:
import java.io.*;
class Stack {
int top;
boolean isEmpty()
Stack()
top = -1;
boolean push(int x)
10
{
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
11
class Main {
s.push(10);
s.push(20);
s.push(30);
s.print();
OUTPUT:
RESULT:
Thus the java application to generate implementation of stack using classes and
objects was implemented and executed successfully.
12
EX.NO.2(B) QUEUE ADT USING CLASSES AND OBJECTS
DATE:
AIM:
ALGORITHM:
PROGRAM:
// implementation of queue
import java.io.*;
classQueue {
intcapacity;
intarray[];
13
publicQueue(intcapacity)
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = newint[this.capacity];
booleanisFull(Queue queue)
return(queue.size == queue.capacity);
booleanisEmpty(Queue queue)
return(queue.size == 0);
voidenqueue(intitem)
14
{
if(isFull(this))
return;
this.array[this.rear] = item;
this.size = this.size + 1;
intdequeue()
if(isEmpty(this))
returnInteger.MIN_VALUE;
intitem = this.array[this.front];
this.size = this.size - 1;
returnitem;
intfront()
15
{
if(isEmpty(this))
returnInteger.MIN_VALUE;
returnthis.array[this.front];
intrear()
if(isEmpty(this))
returnInteger.MIN_VALUE;
returnthis.array[this.rear];
// Driver class
publicclassTest {
publicstaticvoidmain(String[] args)
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
16
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
RESULT:
Thus the java application to generate implementation of queue using classes and
objects was implemented and executed successfully.
17
EX.NO.3 PROGRAM TO GENERATE PAYSLIP
DATE:
AIM:
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:
import java.io.*;
import java.util.*;
class employee
int empid;
long mobile;
void getdata()
name = get.nextLine();
18
System.out.println("Enter Mail id");
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);
19
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);
20
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 getassociate()
bp = get.nextDouble();
void calculateassociate()
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
21
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);
22
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)
23
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:
24
professor prof=new professor();
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
cont=c.nextInt();
}while(cont==1);
OUTPUT:
25
RESULT:
Thus the java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.
26
EX.NO.4 PROGRAM TO CALCULATE AREA USING ABSTRACT CLASS
DATE:
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.io.*;
import java.util.*;
float area;
area= x * y;
27
class Triangle extends Shape {
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();
28
break;
case 2:
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3:
c.x = sc.nextInt();
c.printArea();
break;
29
OUTPUT:
RESULT:
Thus a java program to calculate the area of rectangle, circle and triangle was
implemented and executed successfully.
30
EX.NO.5 PROGRAM TO CALCULATE AREA USING INTERFACE
DATE:
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 rectangle 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 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:
import java.io.*;
interface Shape
void input();
void area();
int r = 0;
double pi = 3.14, ar = 0;
@Override
{
31
r = 5;
@Override
ar = pi * r * r;
System.out.println("Area of circle:"+ar);
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);
32
{
obj.input();
obj.area();
OUTPUT:
$ javac Demo.java
$ java Demo
Area of circle:78.5
Area of rectangle:24.0
RESULT:
Thus a java application to calculate the area of rectangle and circle was implemented
using interface and the program is executed successfully.
33
EX.NO.6 PROGRAM TO IMPLEMENT USER DEFINED EXCEPTION
DATE: 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.io.*;
import java.util.Scanner;
String msg;
NegativeAmtException(String msg)
this.msg=msg;
return msg;
}
34
public class userdefined
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);
35
OUTPUT:
(b) PROGRAM:
ALGORITHM:
PROGRAM:
import java.io.*;
class MyException extends Exception{
String str1;
MyException(String str2)
str1=str2;
36
class example
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.
37
EX.NO.7 PROGRAM TO IMPLEMENT MULTITHREADED APPLICATION
DATE:
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.io.*;
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) {
38
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("------------------------------------");
39
catch (Exception ex) {
System.out.println(ex.getMessage());
// Driver class
rand_num.start();
OUTPUT:
RESULT:
40
EX.NO.8(A) FILE CREATION
DATE:
AIM:
ALGORITHM:
PROGRAM:
import java.io.*;
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:
RESULT:
Thus the java program to create a new file has been implemented and executed
successfully.
41
EX.NO.8(B) DISPLAYING FILE PROPERTIES
DATE:
AIM:
To read and display a file’s properties.
ALGORITHM:
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.io.*;
import java.util.Scanner;
import java.io.File;
class fileDemo
String s = input.nextLine();
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
RESULT:
Thus the java program to read and display a file’s properties has been implemented
and executed successfully.
43
EX.NO.8(C) WRITE CONTENT INTO FILE
DATE:
AIM:
ALGORITHM:
PROGRAM:
import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
try {
if (objFile.exists() == false) {
if (objFile.createNewFile()) {
44
} 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.");
45
OUTPUT:
RESULT:
Thus the java program to write a content into a file has been implemented and
executed successfully.
46
EX.NO.8(D) READ CONTENT FROM FILE
DATE:
AIM:
ALGORITHM:
Step3: FileInputStream.read() method which returns an integer value and will read
values until -1 is not found
PROGRAM:
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
try {
if (objFile.exists() == false) {
System.exit(0);
String text;
int val;
//object of FileOutputStream
47
//read text from file
System.out.print((char) val);
System.out.println();
fileIn.close();
OUTPUT:
RESULT:
Thus the java program to write a java program to read content from the file has been
implemented and executed successfully.
48
EX.NO.9 GENERIC PROGRAMMING
DATE:
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:
import java.io.*;
class MyClass<T extends Comparable<T>>
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;
49
}
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};
50
OUTPUT:
RESULT:
Thus the java program to find the maximum value from the given type of elements
has been implemented using generics and executed successfully.
51
EX.NO.10(A) DEVELOP APPLICATIONS USING JAVAFX CONTROLS
DATE:
AIM:
ALGORITHM:
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;
52
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);
54
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;");
55
OUTPUT:
RESULT:
Thus the java application to develop applications using JavaFX controls has been
implemented using JavaFX and executed successfully.
56
EX.NO.10(B) DEVELOP APPLICATIONS USING JAVAFX LAYOUTS
DATE:
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;
57
import javafx.scene.control.TextField;
import javafx.geometry.Insets;
@Override
pane.setHgap(5);
pane.setVgap(5);
tfMi.setPrefColumnCount(1);
new TextField());
primaryStage.setTitle("ShowFlowPane");
launch(args);
58
OUTPUT:
RESULT:
Thus the java application to develop a java applications using JavaFX layouts
has been implemented using JavaFX and executed successfully.
59
EX.NO.10(C) DEVELOP APPLICATIONS USING JAVAFX MENUS
DATE:
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);
60
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 + "");
61
};
public static void main(String[] args) {
launch(args);
}
}
OUTPUT:
RESULT:
Thus the java application to develop a java applications using JavaFX menus
62
EX.NO:11 SCIENTIFIC CALCULATOR
DATE:
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);
63
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);
64
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");
65
} 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");
66
} 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("");
67
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("");
68
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("");
69
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);
70
}
}
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) {
}
71
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}
OUTPUT:
RESULT:
Thus the java application to develop scientific calculator application using AWT and
Swing was implemented and executed successfully.
72
EX.NO.12 DECISION MAKING STATEMENTS
DATE:
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:
RESULT:
Thus the program to find largest of three numbers was executed and implemented
successfully.
73
EX.NO.13 IMPLEMENTING STRING FUNCTIONS
DATE:
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:
74
OUTPUT:
RESULT:
Thus the program to create a JAVA program to implement the string operation was
implemented and executed successfully.
75
EX.NO.14 DESIGN APPLET
DATE:
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>
76
OUTPUT:
RESULT:
Thus the program to demonstrate use of Graphics Programming to display different
shapes and msg using Applet was implemented and executed successfully.
77
EX.NO.15 IMPLEMENTING GRAPHIC CLASS METHODS
DATE:
AIM:
Program to implement use of Graphics class methods to display different shapes and
msg using Applet.
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:
78
RESULT:
Thus the program to implement use of Graphics class methods to display different
shapes and msg using Applet was implemented and executed successfully.
79
80