OOPS Manual
OOPS Manual
SYLLABUS
TOTAL : 45 PERIODS
1
COURSE OUTCOMES
2
A) Sequential Search
AIM:
To Develop a Java application to solve problems by using sequential search.
PROCEDURE:
Let the element to be search be x.
1.
Start from the leftmost element of arr[] and one by one compare x with each element of arr[].
2.
If x matches with an element then return that index.
3.
If x doesn’t match with any of elements then return -1
4.
PROGRAM:
import [Link].*;
class sequential
{
// Element to search
int x = 10;
// Function Call
int result = search(arr,
x); if (result == -1)
3
OUTPUT:
RESULT
Thus the Java application to solve problems by using sequential search was implemented
and verified successfully.
4
B) Binary Search
AIM:
PROGRAM:
import [Link].*;
class Main{
public static void main(String args[]){
int numArray[] = {5,10,15,20,25,30,35};
[Link]("The input array: " + [Link](numArray));
//key to be searched
int key = 20;
[Link]("\nKey to be searched=" + key);
//set first to first
index int first = 0;
//set last to last elements in
array int last=[Link]-
1;
//calculate mid of the
array int mid = (first +
last)/2;
//while first and last do not
overlap while( first <= last ){
//if the mid < key, then key to be searched is in the first half of
array if ( numArray[mid] < key ){
first = mid + 1;
}else if ( numArray[mid] == key ){
//if key = element at mid, then print the location
[Link]("Element is found at index: " +
mid); break;
}else{
//the key is to be searched in the second half of the
array last = mid - 1;
}
mid = (first + last)/2;
}
5
//if first and last overlap, then key is not present in the
array if ( first > last ){
[Link]("Element is not found!");
}
}
}
OUTPUT:
RESULT
Thus the Java application to solve problems by using binary search was implemented
and Verified successfully.
6
C) SELECTION SORT
AIM:
1. Finding the minimum value in the unsorted array and move it to the first position.
2. Now increase the pointer value by 1.
3. Again start searching for next minimal value in array (except in previous one)
4. If found minimal swap the value to second position element
5. Else leave it move pointer next
6. Sort the remaining values of data set (excluding the previous value).
PROGRAM:
public class SelectionSortEx {
public static void main(String a[]) {
//Numbers which are to be sorted
int n[] = {55,33, 22,88,99,44,11,77,66};
//Displays the numbers before sorting
[Link]("Before sorting, numbers are
"); for (int i = 0; i < [Link]; i++) {
[Link](n[i] + " ");
}
[Link]();
//Sorting in ascending order using bubble
sort initializeselectionSort(n);
//Displaying the numbers after sorting
[Link]("After sorting, numbers are
"); for (int i = 0; i < [Link]; i++) {
[Link](n[i] + " ");
}
}
//This method sorts the input array in descending
order public static void initializeselectionSort(int n[])
{
int i, j, first, temp;
for (i = [Link] - 1; i > 0; i--) {
first = 0; //initialize to subscript of first element
for (j = 1; j <= i; j++) //locate smallest element between 1 and i.
{
if (n[j] <
n[first]) first
= j;
}
temp = n[first]; //swap the smallest found in position
i. n[first] = n[i];
n[i] = temp;
}
}
}
7
OUTPUT:
RESULT
Thus the Java application to solve problems by using selection sort was implemented
and Verified successfully.
8
D) INSERTION SORT
AIM:
9
OUTPUT:
RESULT
Thus the Java application to solve problems by using insertion sort was implemented
and Verified successfully.
10
A) STACK IMPLEMENTATION
AIM:
To Develop a Java application to implement stack using classes and objects.
ALGORITHM:
1. push inserts an item at the top of the stack (i.e., above its current top element).
2. pop removes the object at the top of the stack and returns that object from the function.
The stack size will be decremented by one.
3. isEmpty tests if the stack is empty or not.
4. isFull tests if the stack is full or not.
5. peek returns the object at the top of the stack without removing it from the stack
or modifying the stack in any way.
6. size returns the total number of elements present in the stack.
PROGRAM:
class Stack
{
private int arr[];
private int top;
private int capacity;
// Constructor to initialize the
stack Stack(int size)
{
arr = new
int[size]; capacity
= size; top = -1;
}
// Utility function to add an element `x` to the
stack public void push(int x)
{
if (isFull())
{
[Link]("Overflow\nProgram Terminated\n");
[Link](-1);
}
[Link]("Inserting " +
x); arr[++top] = x;
}
// Utility function to pop a top element from the
stack public int pop()
{
// check for stack
underflow if (isEmpty())
{
[Link]("Underflow\nProgram Terminated");
[Link](-1);
}
[Link]("Removing " + peek());
// decrease stack size by 1 and (optionally) return the popped
element return arr[top--];
11
}
// Utility function to return the top element of the
stack public int peek()
{
if (!isEmpty()) {
return arr[top];
}
else {
[Link](-1);
}
return -1;
}
// Utility function to return the size of the
stack public int size() {
return top + 1;
}
// Utility function to check if the stack is empty or
not public boolean isEmpty() {
return top == -1; // or return size() == 0;
}
// Utility function to check if the stack is full or
not public boolean isFull() {
return top == capacity - 1; // or return size() == capacity;
}
}
class Main
{
public static void main (String[] args)
{
Stack stack = new Stack(3);
[Link](1); // inserting 1 in the stack
[Link](2); // inserting 2 in the stack
[Link](); // removing the top element (2)
[Link](); // removing the top element (1)
[Link](3); // inserting 3 in the stack
[Link]("The top element is " +
[Link]()); [Link]("The stack size is " +
[Link]()); [Link](); // removing the top element
(3)
// check if the stack is empty
if ([Link]()) {
[Link]("The stack is empty");
}
else {
[Link]("The stack is not empty");
}
}
}
12
OUTPUT:
RESULT
Thus the Java application of Stack data structure has been implemented and Verified successfully.
13
B) QUEUE IMPLEMENTATION
AIM:
To Develop a Java application to implement queue using classes and objects.
ALGORITHM:
1. Enqueue: Inserts an item at the rear of the queue.
2. Dequeue: Removes the object from the front of the queue and returns it,
thereby decrementing queue size by one.
3. Peek: Returns the object at the front of the queue without removing it.
4. IsEmpty: Tests if the queue is empty or not.
5. Size: Returns the total number of elements present in the queue.
PROGRAM:
// Constructor to initialize a
queue Queue(int size)
{
arr = new
int[size]; capacity
= size; front = 0;
rear = -1;
count = 0;
}
// Utility function to dequeue the front
element public int dequeue()
{
// check for queue
underflow if (isEmpty())
{
[Link]("Underflow\nProgram Terminated");
[Link](-1);
}
14
int x = arr[front];
[Link]("Removing " +
x); front = (front + 1) % capacity;
count--;
return x;
}
// Utility function to add an item to the
queue public void enqueue(int item)
{
// check for queue
overflow if (isFull())
{
[Link]("Overflow\nProgram Terminated");
[Link](-1);
}
[Link]("Inserting " + item);
rear = (rear + 1) % capacity;
arr[rear] = item;
count++;
}
// Utility function to return the front element of the
queue public int peek()
{
if (isEmpty())
{
[Link]("Underflow\nProgram Terminated");
[Link](-1);
}
return arr[front];
}
// Utility function to return the size of the
queue public int size() {
return count;
}
// Utility function to check if the queue is empty or
not public boolean isEmpty() {
return (size() == 0);
15
// Utility function to check if the queue is full or
not public boolean isFull() {
return (size() == capacity);
}
}
class Main
{
public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);
[Link](1);
[Link](2);
[Link](3);
[Link]("The front element is " +
[Link]()); [Link]();
[Link]("The front element is " +
[Link]()); [Link]("The queue size is " +
[Link]()); [Link]();
[Link]();
if ([Link]()) {
[Link]("The queue is empty");
}
else {
[Link]("The queue is not empty");
} } }
OUTPUT:
RESULT
Thus the Java application of Queue data structure has been implemented and Verified
successfully.
16
Expt. No: 3 EMPLOYEE SALARY CALCULATION USING INHERITANCE
CONCEPTS
AIM:
To develop a java application with Employee class with Emp_name, Emp_id,
Address, Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant
Professor, Associate Professor and Professor from employee class and Generate pay slips for
the employees with their gross and net salary with respected to given statements below.
PROCEDURE:
1. Create a base class Employee, necessary members and methods to read / display the
employee information.
2. Create subclasses Programmer, AssistantProfessor, AssociateProfessor and Professor
derived from Employee class and overload and override methods
like(getEmployeeDetails(basicPay) and display(). in addition cal() method which is
used to salary calculation based on employee designation with respected to problem
statements.
PROGRAM
import [Link];
public class EmployeeSalaryCalc
{ public static void main(String args[]){
Scanner obj=new Scanner([Link]);
Programmer p=new Programmer();
[Link]("Enter the basic pay of
Programmer"); [Link]([Link]());
[Link]();
AssistantProfessor ap=new AssistantProfessor();
[Link]("Enter the basic pay of Assistant
Professor"); [Link]([Link]());
[Link]();
AssociateProfessor asp=new AssociateProfessor();
[Link]("Enter the basic pay of Associate
Professor"); [Link]([Link]());
[Link]();
Professor prof=new Professor();
[Link]("Enter the basic pay of
Professor");
[Link]([Link]());
[Link]();
}
}
class Employee{
String employeeName;
int employeeID;
String address;
String mailID;
long mobileNumber;
double da,hra,pf,sc,ns,gs;
Scanner obj=new
Scanner([Link]); void
getEmployeeDetails(){
17
[Link]("Enter the Employee Name:");
employeeName=[Link]();
[Link]("Enter the Employee Address:");
address=[Link]();
[Link]("Enter the Employee Mail
ID:"); mailID=[Link]();
[Link]("Enter the Employee
ID:"); employeeID=[Link]();
[Link]("Enter the Employee Mobile
Number:"); mobileNumber=[Link]();
}
void display(){
[Link]("Employee Name :"+employeeName);
[Link]("Employee ID :"+employeeID);
[Link]("Employee Address :"+address);
[Link]("Employee Mail ID :"+mailID);
[Link]("Employee Mobile Number:"+mobileNumber);
}
}
class Programmer extends
Employee{ double basicPay;
public double getBasicPay()
{ return basicPay;
}
public void setBasicPay(double basicPay)
{ [Link] = basicPay;
}
void getEmployeeDetails(double bp){
[Link]();
setBasicPay(bp);
}
void cal(){
da=getBasicPay()*97/100.0;
hra=getBasicPay()*10/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*1/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
}
void display(){
[Link]();
[Link]("Employee Gross Salary:"+gs);
[Link]("Employee Net Salary :"+ns);
}}
class AssistantProfessor extends Employee{
18
19
double basicPay;
public double getBasicPay() {return basicPay;
}
public void setBasicPay(double basicPay) {
[Link] = basicPay;
}
void getEmployeeDetails(double bp){
[Link]();
setBasicPay(bp);
}
void cal(){
da=getBasicPay()*110/100.0;
hra=getBasicPay()*20/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*5/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
}
void display(){
[Link]();
[Link]("Employee Gross Salary:"+gs);
[Link]("Employee Net Salary :"+ns);
}}
class AssociateProfessor extends
Employee{ double basicPay;
public double getBasicPay() {
return basicPay;
}
public void setBasicPay(double basicPay)
{ [Link] = basicPay;
}
void getEmployeeDetails(double bp){
[Link]();
setBasicPay(bp);
}
void cal(){
da=getBasicPay()*130/100.0;
hra=getBasicPay()*30/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*10/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
}
void display(){
20
[Link]();
[Link]("Employee Gross Salary:"+gs);
[Link]("Employee Net Salary :"+ns);
}}
class Professor extends
Employee{ [Link] =
basicPay;
}
void getEmployeeDetails(double bp){
[Link]();
setBasicPay(bp);
}
void cal(){
da=getBasicPay()*140/100.0;
hra=getBasicPay()*40/100.0;
pf=getBasicPay()*12/100.0;
sc=getBasicPay()*15/100.0;
gs=getBasicPay()+da+hra+pf+sc;
ns=gs-pf-sc;
display();
}
void display(){
[Link]();
[Link]("Employee Gross Salary:"+gs);
[Link]("Employee Net Salary :"+ns);
}}
21
OUTPUT:
Enter the basic pay of Programmer
15000
Enter the Employee Name:
ram
Enter the Employee Address:
56 Ganga Street
Enter the Employee Mail
ID: ram@[Link]
Enter the Employee ID:
101
Enter the Employee Mobile
Number: 9994117284
Employee Name :ram
Employee ID 101
Employee Address :56 Ganga Street
Employee Mail ID :ram@[Link]
Employee Mobile Number:9994117284
Employee Gross Salary:33000.0
Employee Net Salary :31050.0
Enter the basic pay of Assistant Professor
20000
Enter the Employee Name:
vinu
Enter the Employee Address:
75 public office road
Enter the Employee Mail
ID: vinu@[Link]
Enter the Employee ID:
201
Enter the Employee Mobile
Number: 9842321130
Employee Name :vinu
Employee ID 201
Employee Address :75 public office
road Employee Mail ID:vinu@[Link]
Employee Mobile Number:9842321130
Employee Gross Salary:49400.0
Employee Net Salary :46000.0
22
Enter the basic pay of Associate Professor
30000
Enter the Employee Name:
krish
Enter the Employee Address:
25 neela east street
Enter the Employee Mail
ID: krish@[Link]
Enter the Employee ID:
301
Enter the Employee Mobile
Number: 9578621131
Employee Name :krish
Employee ID 301
Employee Address :25 neela east
street Employee Mail ID :krish@[Link]
Employee Mobile Number:9578621131
Employee Gross Salary :84600.0 Employee
Net Salary :78000.0
Enter the basic pay of Professor
40000
Enter the Employee
Name: vinayagam
Enter the Employee Address:
100 Nehru Street
Enter the Employee Mail
ID: vinayagam@[Link]
Enter the Employee ID:
401
Enter the Employee Mobile
Number: 7904923391
Employee Name :vinayagam
Employee ID 401
Employee Address :100 Nehru Street
Employee Mail ID :vinayagam@[Link]
Employee Mobile Number:7904923391
Employee Gross Salary:122800.0
Employee Net Salary :112000.0
RESULT
Thus the java program to calculate the employee salary using inheritance concepts was
implemented and verified successfully.
23
Expt. No: 4
ABSTRACT CLASS
AIM:
To write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each one of
the classes contains only the method print Area () that prints the area of the given shape.
PROCEDURE:
1. Create a class Shape with necessary members and abstract method printArea()
2. Create sub classes Rectangle and Triangle derived from Shape and override
the printArea()
PROGRAM
import [Link].*;
abstract class
shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
[Link]("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
[Link]("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
[Link]("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new
Rectangle(); [Link](2,5);
Circle c=new Circle();
24
[Link](5,5);
Triangle t=new
Triangle(); [Link](2,5);
}
}
OUTPUT:
RESULT
Thus the java program to demonstrate Abstract Class was implemented and
verified successfully.
25
Expt. No: 5
INTERFACE
AIM:
To write a Java Program to create an interface named Shape that contains two methods
input() and area(). Provide two classes named Rectangle, and Circle such that each one of
the classes extends the class Shape. Each one of the classes contains the necessary
methods that prints the area of the given shape.
PROCEDURE:
1. Create a class Demo with necessary members and an interface Shape.
2. Create sub classes Rectangle and Circle derived from Shape and override
the methods input() and area().
PROGRAM:
interface Shape
{
void input();
void area();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar =
0; @Override
public void input()
{
r = 5;
}
@Override
public void
area()
{
ar = pi * r * r;
[Link]("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{
int l = 0, b =
0; double ar;
26
public void input()
27
{
[Link]();
l = 6;
b = 4;
}
public void area()
{
[Link]();
ar = l * b;
[Link]("Area of rectangle:"+ar);
}
}
public class Demo
{
public static void main(String[] args)
{
Rectangle obj = new
Rectangle(); [Link]();
[Link]();
}
}
Output:
RESULT
Thus the java program to demonstrate interface was implemented and verified successfully.
28
Expt. No: 6
USER DEFINED EXCEPTION HANDLING
AIM:
To write a java program to implement user defined exception handling
ALGORITHM:
Step [Link] a class which extends Exception class.
Step [Link] a constructor which receives the string as
argument. Step [Link] the Amount as input from the user.
Step [Link] the amount is negative , the exception will be generated.
Step [Link] the exception handling mechanism , the thrown exception is handled by the
catch construct.
Step [Link] the exception is handled , the string “invalid amount “ will be displayed.
Step [Link] the amount is greater than 0 , the message “Amount Deposited “ will be displayed
PROGRAM:
import [Link];
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
[Link]=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
[Link]("Enter Amount:");
int a=[Link]();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
[Link]("Amount Deposited");
}
catch(NegativeAmtException e)
{
[Link](e);
}
}
}
29
OUTPUT:
RESULT:
Thus a java program to implement user defined exception handling has been implemented
and Verified successfully.
30
Expt. No: 7
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.
[Link] a third thread that generates random [Link] the random number is even , it
displays
the square of the [Link] the random number generated is odd , it displays the cube of the
given number .
[Link] Multithreading is performed and the task switched between multiple
threads. [Link] sleep () method makes the thread to suspend for the specified time.
PROGRAM
[Link]
import [Link].*;
// class for Even Number
class EvenNum implements Runnable
{ public int a;
public EvenNum(int a)
{ this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable
{ public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
[Link]("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread
{ public void run() {
int n = 0;
Random rand = new
Random(); try {
for (int i = 0; i < 10; i++)
{ n = [Link](20);
31
[Link]("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new
EvenNum(n)); [Link]();
}
else {
Thread thread2 = new Thread(new
OddNum(n)); [Link]();
}
// thread wait for 1
second
[Link](1000);
[Link](" ");
}
}
catch (Exception ex) {
[Link]([Link]());
}
}
}
// Driver class
public class MultiThreadRandOddEven
{ public static void main(String[]
args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
Output:
RESULT:
32
Thus a java program implements a multi-threaded application was verified successfully.
33
Expt. No: 8(a)
FILE CREATION
AIM
To write a java program to create a new file
ALGORITHM:
PROGRAM
import [Link];
// Importing the IOException class for handling errors
import [Link];
class CreateFile {
public static void main(String args[])
{ try {
// Creating an object of a file
File f0 = new File("D:[Link]");
if ([Link]()) {
[Link]("File " + [Link]() + " is created successfully.");
} else {
[Link]("File is already exist in the directory.");
}
} catch (IOException exception) {
[Link]("An unexpected error is
occurred."); [Link]();
}
}
}
OUTPUT
34
Expt. No: 8(b)
DISPLAYING FILE PROPERTIES
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 [Link];
import [Link];
class fileDemo{
public static void main(String[] args){
[Link]("Enter the file
name:"); Scanner input = new
Scanner([Link]); String s =
[Link]();
File f1=new File(s);
[Link]("-------------------------");
[Link]("File Name: " +[Link]());
[Link]("Path: " +[Link]());
[Link]("Abs Path: "
+[Link]());
[Link]("This file: " +([Link]()?"Exists":"Does not
exists")); [Link]("File: " +[Link]());
[Link]("Directory: " +[Link]());
[Link]("Readable: " +[Link]());
[Link]("Writable: " +[Link]());
[Link]("Absolute: " +[Link]());
[Link]("File Size: " +[Link]()+ "bytes");
[Link]("Is Hidden: " +[Link]());
}}
OUTPUT:
C:\ >javac [Link]
C:\ >java fileDemo
Enter the file name:
[Link]
File Name:
[Link] Path:
[Link]
Abs Path: D:\ Ex 08\
[Link] This file: Exists
File: true
Directory: false
Readable: true
Writable: true
35
Absolute: false
File Size:
895bytes Is
Hidden: false
36
Expt. No: 8(c)
Write Content into File
AIM
To write a content into file
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
[Link](),[Link](),[Link]()
Step 6: [Link]() - returns the bytes array.
Step 7: [Link]() - Is used to clear the output steam buffer.
Step 8: [Link]() - Is used to close output stream (Close the
file). Step 9: Stop the program
PROGRAM
import [Link];
import [Link];
import [Link];
public class WriteFile {
public static void main(String args[])
{ final String fileName = "[Link]";
try {
File objFile = new
File(fileName); if ([Link]()
== false) {
if ([Link]()) {
[Link]("File created successfully.");
} else {
[Link]("File creation failed!!!");
[Link](0);
}
}
//writting data into
file String text;
Scanner SC = new Scanner([Link]);
[Link]("Enter text to write into file:
"); text = [Link]();
//object of FileOutputStream
FileOutputStream fileOut = new FileOutputStream(objFile);
//convert text into Byte and write into
file [Link]([Link]());
[Link]();
[Link]();
[Link]("File saved.");
} catch (Exception Ex) {
37
[Link]("Exception : " + [Link]());
}
}
}
OUTPUT
38
Expt. No: 8(d)
Read Content from File
AIM
Write a java program to read content from the file
ALGORITHM
Step 1: Start the program
Step 2: Read the content of the file using FileInputStream
Step 3: [Link]() method which returns an integer value and will read values
until -1 is not found
Step 4: Stop the program
PROGRAM
import [Link];
import [Link];
public class ReadFile {
public static void main(String args[])
{ final String fileName = "[Link]";
try {
File objFile = new
File(fileName); if ([Link]()
== false) {
[Link]("File does not
exist!!!"); [Link](0);
}
//reading content from
file String text;
int val;
//object of FileOutputStream
FileInputStream fileIn = new FileInputStream(objFile);
//read text from file
[Link]("Content of the file is: ");
while ((val = [Link]()) != -1) {
[Link]((char) val);
}
[Link]();
[Link]();
} catch (Exception Ex) {
[Link]("Exception : " +
[Link]());
}
}
}
39
OUTPUT
RESULT:
Thus the File operations using java program was implemented and
verified successfully.
40
Expt. No: 9
GENERIC PROGRAMMING
AIM:
To write a java program to find the maximum value from the given type of elements using a generic
function.
ALGORITHM:
PROGRAM
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < [Link]; i+
+) if(vals[i].compareTo(v) < 0)
v=
vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i < [Link];i+
+) if(vals[i].compareTo(v) >
0)
v=
vals[i];
return v;
}
}
class gendemo
{
public static void main(String args[])
{
41
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
42
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
OUTPUT
RESULT:
Thus a java program to find the maximum value from the given type of elements
using a generic function was successfully completed.
.
43
Expt. No: 10(a)
DEVELOP APPLICATIONS USING JAVAFX
CONTROLS AIM:
ALGORITHM
PROGRAM
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
44
public class Registration extends Application
{ @Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");
46
//list View for educational qualification
ObservableList<String> names = [Link](
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil",
"Phd");
ListView<String> educationListView = new ListView<String>(names);
[Link](dobLabel, 0, 1);
[Link](datePicker, 1, 1);
[Link](genderLabel, 0, 2);
[Link](maleRadio, 1, 2);
[Link](femaleRadio, 2, 2);
[Link](reservationLabel, 0, 3);
[Link](yes, 1, 3);
[Link](no, 2, 3);
[Link](technologiesLabel, 0, 4);
[Link](javaCheckBox, 1, 4);
47
[Link](dotnetCheckBox, 2, 4);
48
[Link](educationLabel, 0, 5);
[Link](educationListView, 1, 5);
[Link](locationLabel, 0, 6);
[Link](locationchoiceBox, 1, 6);
[Link](buttonRegister, 2, 8);
//Styling nodes
[Link]("-fx-background-color: darkslateblue; -fx-textfill: white;");
[Link]("-fx-font: normal bold 15px 'serif' ");
[Link]("-fx-font: normal bold 15px 'serif' ");
[Link]("-fx-font: normal bold 15px 'serif' ");
[Link]("-fx-font: normal bold 15px 'serif' ");
[Link]("-fx-font: normal bold 15px 'serif'
"); [Link]("-fx-font: normal bold 15px 'serif'
"); [Link]("-fx-font: normal bold 15px 'serif' ");
//Setting the back ground color
[Link]("-fx-background-color: BEIGE;");
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
[Link]("Registration Form");
//Adding scene to the stage
[Link](scene);
//Displaying the contents of the
stage [Link]();
}
public static void main(String args[])
{ launch(args);
}
}
OUTPUT
49
Expt. No: 10(b)
DEVELOP APPLICATIONS USING JAVAFX
LAYOUTS AIM
To develop a java applications using JavaFX layouts
ALGORITHM
Step 1: Creating a Class
Create a Java class and inherit the Application class of the package [Link]
and implement the start() method
Step 2: Creating a Scene Object
Create a Scene by instantiating the class named Scene which belongs to the package [Link].
Step 3: Setting the Title of the Stage
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.
Step 4: Adding Scene to the Stage
You can add a Scene object to the stage using the method setScene() of the class named
Stage. Step 5: Displaying the Contents of the Stage
Display the contents of the scene using the method named show() of the Stage
class Step 6: Launching the Application
Launch the JavaFX application by calling the static method launch() of the Application class
from the main method
PROGRAM
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ShowFlowPane extends Application
{ @Override
public void start(Stage primaryStage) {
FlowPane pane = new FlowPane();
[Link](new Insets(11, 12, 13, 14));
[Link](5);
[Link](5);
// Place nodes in the pane
[Link]().addAll(new Label("First
Name:"), new TextField(), new Label("MI:"));
TextField tfMi = new TextField();
[Link](1);
[Link]().addAll(tfMi, new Label("Last
Name:"), new TextField());
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 210, 150);
[Link]("ShowFlowPane");
[Link](scene); // Place the scene in the
stage [Link](); // Display the stage
}
50
public static void main(String[] args)
{ launch(args);
}
}
OUTPUT
51
Expt. No: 10(c)
DEVELOP APPLICATIONS USING JAVAFX MENUS
AIM
ALGORITHM
PROGRAM
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
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");
[Link]().addAll(menuOperation, menuExit);
MenuItem menuItemAdd = new MenuItem("Add");
MenuItem menuItemSubtract = new MenuItem("Subtract");
MenuItem menuItemMultiply = new
MenuItem("Multiply"); MenuItem menuItemDivide = new
MenuItem("Divide");
52
[Link]().addAll(menuItemAdd, menuItemSubtract,
menuItemMultiply, menuItemDivide);
MenuItem menuItemClose = new
MenuItem("Close");
[Link]().add(menuItemClose);
53
[Link]( KeyCombinatio
[Link]("Ctrl+A"));
[Link]( KeyCombi
[Link]("Ctrl+S"));
[Link]( KeyCombi
[Link]("Ctrl+M"));
[Link]( KeyCombina
[Link]("Ctrl+D")); HBox
hBox1 = new HBox(5);
[Link](2);
[Link](2);
[Link](2);
[Link]().addAll(new Label("Number 1:"),
tfNumber1, new Label("Number 2:"), tfNumber2, new
Label("Result:"), tfResult);
[Link]([Link]);
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");
[Link]().addAll(btAdd, btSubtract, btMultiply,
btDivide); [Link]([Link]);
VBox vBox = new VBox(10);
[Link]().addAll(menuBar, hBox1, hBox2);
Scene scene = new Scene(vBox, 300, 250);
[Link]("MenuDemo"); // Set the window
title
[Link](scene); // Place the scene in the
window [Link](); // Display the window
// Handle menu actions
[Link](e -> perform('+'));
[Link](e -> perform('-'));
[Link](e -> perform('*'));
[Link](e -> perform('/'));
[Link](e -> [Link](0));
// Handle button actions
[Link](e -> perform('+'));
[Link](e -> perform('-'));
[Link](e -> perform('*'));
[Link](e -> perform('/'));
}
private void perform(char operator) {
double number1 = [Link]([Link]());
double number2 = [Link]([Link]());
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;
54
}
55
[Link](result + "");
};
public static void main(String[] args)
{ launch(args);
}
}
OUTPUT
RESULT:
Thus the java program to develop applications using JavaFX controls, Layouts and menus was
implemented and verified successfully.
56
Expt. No: 11 SCIENTIFIC CALCULATOR
AIM:
To develop scientific calculator application using AWT and Swing.
ALGORITHM
Step 1: Start the program.
Step 2: import awt and swing and event packages.
Step 3: Declare variables and use container class to design
buttons. Step 4: Use grid layout and action listener to listen button
actions. Step 5: Use setText() and getText() to set and get text
values.
Step 6: Use [Link] to convert string to Double
Step 7: In main method set LookAndFeel and use requestFocus(), setTitle(), Pack()
and setVisible() methods.
Step 8: Stop the program
PROGRAM
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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();
[Link](new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
[Link]([Link]);
[Link](new KeyAdapter() {
public void keyTyped(KeyEvent keyevent)
{ char c = [Link]();
if (c >= '0' && c <= '9') {
} else {
[Link]();
}
}
57
});
58
[Link](tfield);
buttonpanel = new
JPanel();
[Link](new GridLayout(8, 4, 2,
2)); boolean t = true;
mr = new JButton("MR");
[Link](mr);
[Link](this);
mc = new JButton("MC");
[Link](mc);
[Link](this);
mp = new JButton("M+");
[Link](mp);
[Link](this);
mm = new JButton("M-");
[Link](mm);
[Link](this);
b1 = new JButton("1");
[Link](b1);
[Link](this);
b2 = new JButton("2");
[Link](b2);
[Link](this);
b3 = new JButton("3");
[Link](b3);
[Link](this);
b4 = new JButton("4");
[Link](b4);
[Link](this);
b5 = new JButton("5");
[Link](b5);
[Link](this);
b6 = new JButton("6");
[Link](b6);
[Link](this);
b7 = new JButton("7");
[Link](b7);
[Link](this);
b8 = new JButton("8");
[Link](b8);
[Link](this);
b9 = new JButton("9");
[Link](b9);
[Link](this);
zero = new JButton("0");
[Link](zero);
[Link](this);
plus = new JButton("+");
[Link](plus);
[Link](this);
min = new JButton("-");
[Link](min);
[Link](this);
59
mul = new JButton("*");
60
[Link](mul);
[Link](this);
div = new JButton("/");
[Link](this);
[Link](div);
addSub = new JButton("+/-");
[Link](addSub);
[Link](this);
dot = new JButton(".");
[Link](dot);
[Link](this);
eq = new JButton("=");
[Link](eq);
[Link](this);
rec = new JButton("1/x");
[Link](rec);
[Link](this);
sqrt = new JButton("Sqrt");
[Link](sqrt);
[Link](this);
log = new JButton("log");
[Link](log);
[Link](this);
sin = new JButton("SIN");
[Link](sin);
[Link](this);
cos = new JButton("COS");
[Link](cos);
[Link](this);
tan = new JButton("TAN");
[Link](tan);
[Link](this);
pow2 = new JButton("x^2");
[Link](pow2);
[Link](this);
pow3 = new JButton("x^3");
[Link](pow3);
[Link](this);
exp = new JButton("Exp");
[Link](this);
[Link](exp);
fac = new JButton("n!");
[Link](this);
[Link](fac);
clr = new JButton("AC");
[Link](clr);
[Link](this);
[Link]("Center", buttonpanel);
[Link]("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{ String s = [Link]();
61
if ([Link]("1")) {
if (z == 0) {
[Link]([Link]() + "1");
} else {
[Link]("");
[Link]([Link]() + "1");
z = 0;
}
}
if ([Link]("2")) {
if (z == 0) {
[Link]([Link]() + "2");
} else {
[Link]("");
[Link]([Link]() + "2");
z = 0;
}
}
if ([Link]("3")) {
if (z == 0) {
[Link]([Link]() + "3");
} else {
[Link]("");
[Link]([Link]() + "3");
z = 0;
}
}
if ([Link]("4")) {
if (z == 0) {
[Link]([Link]() + "4");
} else {
[Link]("");
[Link]([Link]() + "4");
z = 0;
}
}
if ([Link]("5")) {
if (z == 0) {
[Link]([Link]() + "5");
} else {
[Link]("");
[Link]([Link]() + "5");
z = 0;
}
}
if ([Link]("6")) {
if (z == 0) {
[Link]([Link]() + "6");
} else {
[Link]("");
[Link]([Link]() + "6");
z = 0;
}
62
}
if ([Link]("7")) {
if (z == 0) {
[Link]([Link]() + "7");
} else {
[Link]("");
[Link]([Link]() + "7");
z = 0;
}
}
if ([Link]("8")) {
if (z == 0) {
[Link]([Link]() + "8");
} else {
[Link]("");
[Link]([Link]() + "8");
z = 0;
}
}
if ([Link]("9")) {
if (z == 0) {
[Link]([Link]() + "9");
} else {
[Link]("");
[Link]([Link]() + "9");
z = 0;
}
}
if ([Link]("0")) {
if (z == 0) {
[Link]([Link]() + "0");
} else {
[Link]("");
[Link]([Link]() + "0");
z = 0;
}
}
if ([Link]("AC")) {
[Link]("");
x = 0;
y = 0;
z = 0;
}
if ([Link]("log")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("1/x")) {
63
if ([Link]().equals("")) {
[Link]("");
} else {
a = 1 / [Link]([Link]());
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("Exp")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("x^2")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()),
2); [Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("x^3")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()),
3); [Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("+/-")) {
if (x == 0) {
[Link]("-" + [Link]());
x = 1;
} else {
[Link]([Link]());
}
}
if ([Link](".")) {
if (y == 0) {
[Link]([Link]() + ".");
y = 1;
} else {
[Link]([Link]());
}}
if ([Link]("+")) {
if ([Link]().equals("")) {
64
[Link]("");
temp = 0;
ch = '+';
} else {
temp = [Link]([Link]());
[Link]("");
ch = '+';
y = 0;
x = 0;
}
[Link]();
}
if ([Link]("-")) {
if ([Link]().equals("")) {
[Link]("");
temp =
0; ch =
'-';
} else
{x=
0;
y = 0;
temp = [Link]([Link]());
[Link]("");
ch = '-';
}
[Link]();
}
if ([Link]("/")) {
if ([Link]().equals("")) {
[Link]("");
temp =
1; ch =
'/';
} else
{x=
0;
y = 0;
temp = [Link]([Link]());
ch = '/';
[Link]("");
}
[Link]();
}
if ([Link]("*")) {
if ([Link]().equals("")) {
[Link]("");
temp =
1; ch =
'*';
} else
{x=
0;
65
y = 0;
temp = [Link]([Link]()); //string to
double ch = '*';
[Link]("");
}
[Link]();
66
}
if ([Link]("MC")) {
m1 = 0;
[Link]("");
}
if ([Link]("MR")) {
[Link]("");
[Link]([Link]() + m1);
}
if ([Link]("M+")) {
if (k == 1) {
m1 = [Link]([Link]());
k++;
} else {
m1 += [Link]([Link]());
[Link]("" + m1);
}
}
if ([Link]("M-")) {
if (k == 1) {
m1 = [Link]([Link]());
k++;
} else {
m1 -=
[Link]([Link]());
[Link]("" + m1);
}
}
if ([Link]("Sqrt")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("SIN")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("COS")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a=
[Link]([Link]([Link]()));
[Link]("");
67
[Link]([Link]() + a);
}
68
}
if ([Link]("TAN")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("=")) {
if ([Link]().equals("")) {
[Link]("");
} else {
temp1 = [Link]([Link]());
switch (ch) {
case '+':
result = temp +
temp1; break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp /
temp1; break;
case '*':
result = temp *
temp1; break;
}
[Link]("");
[Link]([Link]() + result);
z = 1;
}
}
if ([Link]("n!")) {
if ([Link]().equals("")) {
[Link]("");
} else {
a = fact([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
[Link]();
}
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)
69
s *= i;
return s;
}
public static void main(String args[]) {
try {
UIManager
.setLookAndFeel("[Link]");
} catch (Exception e) {
}
ScientificCalculator f = new
ScientificCalculator();
[Link]("ScientificCalculator");
[Link]();
[Link](true);
}
}
OUTPUT
RESULT:
Thus the java program to develop scientific calculator application using AWT and Swing
70
71