0% found this document useful (0 votes)
24 views82 pages

OOPS Record Manual.

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views82 pages

OOPS Record Manual.

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY

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 2: Match the key element with array element

Step 3: If key element is found, return the index position of the array element

Step 4: If key element is not found, return -1

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)

DATE: BINARY SEARCH PROGRAM

AIM:

To develop a Java application to search a key element from multiple elements using
Binary search

ALGORITHM:

Step 1 - Read the search element from the given list.

Step 2 - Find the middle element in the sorted list.

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:

To develop a Java application to sort array elements using selection sort

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;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
6
selectionSort(arr1);//sorting array using selection sort

System.out.println("After Selection Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}

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:

To develop a Java application to sort array elements using insertion sort

ALGORITHM:

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

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.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.

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;
}
}

public static void main(String a[]){


int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");
8
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");


for(int i:arr1){
System.out.print(i+" ");
}
}
}

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:

To design a java application to implement array implementation of stack using


classes and objects

ALGORITHM:

1. Start the program


2. Create the stack operation with method declarations for push and pop.
3. Create the class a stack which implements the methods push and pop. The push
operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Also define the method for displaying the values stored
in the stack.
4. Handle the stack overflow and stack underflow condition.
5. Create the object and invoke the method for push and pop.
6. Stop the program

PROGRAM:

import java.io.*;
class Stack {

static final int MAX = 1000;

int top;

int a[] = new int[MAX]; // Maximum size of Stack

boolean isEmpty()

return (top < 0);

Stack()

top = -1;

boolean push(int x)

10
{

if (top >= (MAX - 1)) {

System.out.println("Stack Overflow");

return false;

else {

a[++top] = x;

System.out.println(x + " pushed into stack");

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--){

System.out.print(" "+ a[i]);

// Driver code

11
class Main {

public static void main(String args[])

Stack s = new Stack();

s.push(10);

s.push(20);

s.push(30);

System.out.println(s.pop() + " Popped from stack");

System.out.print("Elements present in stack :");

s.print();

OUTPUT:

10 pushed into stack


20 pushed into stack
30 pushed into stack
30 Popped from stack
Top element is: 20
Elements present in stack: 20 10

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:

To design a java application to implement array implementation of queue using


Classes and objects

ALGORITHM:

1. Start the program


2. For implementing queue, we need to keep track of two indices, front and rear.
We enqueue an item at the rear and dequeue an item from the front
3. Steps for enqueue:
1. Check the queue is full or not
2. If full, print overflow and exit
3. If queue is not full, increment tail and add the element
4.Steps for dequeue:
1. Check queue is empty or not
2. if empty, print underflow and exit
3. if not empty, print element at the head and increment head
5.Stop the program

PROGRAM:

// Java program for array

// implementation of queue

// A class to represent a queue

import java.io.*;

classQueue {

intfront, rear, size;

intcapacity;

intarray[];

13
publicQueue(intcapacity)

this.capacity = capacity;

front = this.size = 0;

rear = capacity - 1;

array = newint[this.capacity];

// Queue is full when size becomes

// equal to the capacity

booleanisFull(Queue queue)

return(queue.size == queue.capacity);

// Queue is empty when size is 0

booleanisEmpty(Queue queue)

return(queue.size == 0);

// Method to add an item to the queue.

// It changes rear and size

voidenqueue(intitem)

14
{

if(isFull(this))

return;

this.rear = (this.rear + 1)% this.capacity;

this.array[this.rear] = item;

this.size = this.size + 1;

System.out.println(item+ " enqueued to queue");

// Method to remove an item from queue.

// It changes front and size

intdequeue()

if(isEmpty(this))

returnInteger.MIN_VALUE;

intitem = this.array[this.front];

this.front = (this.front + 1)% this.capacity;

this.size = this.size - 1;

returnitem;

// Method to get front of queue

intfront()

15
{

if(isEmpty(this))

returnInteger.MIN_VALUE;

returnthis.array[this.front];

// Method to get rear of queue

intrear()

if(isEmpty(this))

returnInteger.MIN_VALUE;

returnthis.array[this.rear];

// Driver class

publicclassTest {

publicstaticvoidmain(String[] args)

Queue queue = newQueue(1000);

queue.enqueue(10);

queue.enqueue(20);

queue.enqueue(30);

16
queue.enqueue(40);

System.out.println(queue.dequeue()+ " dequeued from queue\n");

System.out.println("Front item is "+ queue.front());

System.out.println("Rear item is "+ queue.rear());

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.

2. Inherit the classes programmer, asstprofessor,associateprofessor and professor from


employee class. 3. Add Basic Pay (BP) as the member of all the inherited classes.

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.

5. Calculate gross salary and net salary.

6. Generate payslip for all categories of employees.

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;

String name, address, mailid;

Scanner get = new Scanner(System.in);

void getdata()

System.out.println("Enter Name of the Employee");

name = get.nextLine();

18
System.out.println("Enter Mail id");

mailid = get.nextLine();

System.out.println("Enter Address of the Employee:");

address = get.nextLine();

System.out.println("Enter employee id ");

empid = get.nextInt();

System.out.println("Enter Mobile Number");

mobile = get.nextLong();

void display()

System.out.println("Employee Name: "+name);

System.out.println("Employee id : "+empid);

System.out.println("Mail id : "+mailid);

System.out.println("Address: "+address);

System.out.println("Mobile Number: "+mobile);

class programmer extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getprogrammer()

System.out.println("Enter basic pay");

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("PAY SLIP FOR PROGRAMMER");

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("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

class asstprofessor extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getasst()

System.out.println("Enter basic pay");

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("PAY SLIP FOR ASSISTANT PROFESSOR");

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("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

class associateprofessor extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getassociate()

System.out.println("Enter basic pay");

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("PAY SLIP FOR ASSOCIATE PROFESSOR");

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("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

class professor extends employee

double salary,bp,da,hra,pf,club,net,gross;

void getprofessor()

System.out.println("Enter basic pay");

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("PAY SLIP FOR PROFESSOR");

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("STAFF CLUB FUND:Rs"+club);

System.out.println("GROSS PAY:Rs"+gross);

System.out.println("NET PAY:Rs"+net);

class salary

public static void main(String args[])

int choice,cont;

do

System.out.println("PAYROLL PROGRAM");

System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE


PROFESSOR \t 4.PROFESSOR ");

System.out.println("Enter Your Choice \t");

Scanner c = new Scanner(System.in);

choice=c.nextInt();

switch(choice)

23
case 1:

programmer p=new programmer();

p.getdata();

p.getprogrammer();

p.display();

p.calculateprog();

break;

case 2:

asstprofessor asst=new asstprofessor();

asst.getdata();

asst.getasst();

asst.display();

asst.calculateasst();

break;

case 3:

associateprofessor asso=new associateprofessor();

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;

System.out.println("Do u want to continue 0 to quit and 1 to continue ");

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.*;

abstract class Shape {

public int x,y;

public abstract void printArea();

class Rectangle1 extends Shape {

public void printArea() {

float area;

area= x * y;

System.out.println("Area of Rectangle is " +area);

27
class Triangle extends Shape {

public void printArea() {

float area;

area= (x * y) / 2.0f;

System.out.println("Area of Triangle is " + area);

class Circle extends Shape {

public void printArea() {

float area;

area=(22 * x * x) / 7.0f;

System.out.println("Area of Circle is " + area);

public class AreaOfShapes {

public static void main(String[] args) {

int choice;

Scanner sc=new Scanner(System.in);

System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area of


Circle ");

System.out.print("Enter your choice : ");

choice=sc.nextInt();

switch(choice) {

case 1:

System.out.println("Enter length and breadth for area of rectangle : ");

Rectangle1 r = new Rectangle1();

r.x=sc.nextInt();

r.y=sc.nextInt();

r.printArea();

28
break;

case 2:

System.out.println("Enter bredth and height for area of traingle : ");

Triangle t = new Triangle();

t.x=sc.nextInt();

t.y=sc.nextInt();

t.printArea();

break;

case 3:

System.out.println("Enter radius for area of circle : ");

Circle c = new Circle();

c.x = sc.nextInt();

c.printArea();

break;

default:System.out.println("Enter correct choice");

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();

class Circle implements Shape

int r = 0;

double pi = 3.14, ar = 0;

@Override

public void input()

{
31
r = 5;

@Override

public void area()

ar = pi * r * r;

System.out.println("Area of circle:"+ar);

class Rectangle extends Circle

int l = 0, b = 0;

double ar;

public void input()

super.input();

l = 6;

b = 4;

public void area()

super.area();

ar = l * b;

System.out.println("Area of rectangle:"+ar);

public class Demo

32
{

public static void main(String[] args)

Rectangle obj = new Rectangle();

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:

To write a java program to implement user defined exception handling

ALGORITHM:

1.Create a class which extends Exception class.

2.Create a constructor which receives the string as argument.

3.Get the Amount as input from the user.

4.If the amount is negative , the exception will be generated.

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;

class NegativeAmtException extends Exception

String msg;

NegativeAmtException(String msg)

this.msg=msg;

public String toString()

return msg;

}
34
public class userdefined

public static void main(String[] args)

Scanner s=new Scanner(System.in);

System.out.print("Enter Amount:");

int a=s.nextInt();

try

if(a<0)

throw new NegativeAmtException("Invalid Amount");

System.out.println("Amount Deposited");

catch(NegativeAmtException e)

System.out.println(e);

35
OUTPUT:

(b) PROGRAM:

ALGORITHM:

1.Create a userdefined exception class called MyException

2.Throw an exception of user defined type as an argument in main()

3.Exception is handled using try, catch block

4.Display the user defined exception

PROGRAM:

import java.io.*;
class MyException extends Exception{

String str1;

MyException(String str2)

str1=str2;

public String toString()

return ("MyException Occurred: "+str1) ;

36
class example

public static void main(String args[])

try

System.out.println("Starting of try block");

throw new MyException("This is My error Message");

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.*;

// class for Even Number

class EvenNum implements Runnable {

public int a;

public EvenNum(int a) {

this.a = a;

public void run() {

System.out.println("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) {
38
this.a = a;

public void run() {

System.out.println("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 = rand.nextInt(20);

System.out.println("Generated Number is " + n);

// check if random number is even or odd

if (n % 2 == 0) {

Thread thread1 = new Thread(new EvenNum(n));

thread1.start();

else {

Thread thread2 = new Thread(new OddNum(n));

thread2.start();

// thread wait for 1 second

Thread.sleep(1000);

System.out.println("------------------------------------");

39
catch (Exception ex) {

System.out.println(ex.getMessage());

// Driver class

public class MultiThreadRandOddEven {

public static void main(String[] args) {

RandomNumGenerator rand_num = new RandomNumGenerator();

rand_num.start();

OUTPUT:

RESULT:

Thus multithreading using java program was verified and implemented.

40
EX.NO.8(A) FILE CREATION
DATE:

AIM:

Write a java program to create a new file

ALGORITHM:

Step1: Start the program


Step2: createNewFile() method is used for creating a file
Step3:createNewFile() method returns true when it successfully creates a new file and
returns false when the file already exists

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

public static void main(String[] args)

System.out.println("Enter the file name:");

Scanner input = new Scanner(System.in);

String s = input.nextLine();

File f1=new File(s);

System.out.println("-------------------------");

System.out.println("File Name: " +f1.getName());

System.out.println("Path: " +f1.getPath());

System.out.println("Abs Path: " +f1.getAbsolutePath());

System.out.println("This file: " +(f1.exists()?"Exists":"Does not exists"));

System.out.println("File: " +f1.isFile());

System.out.println("Directory: " +f1.isDirectory());

System.out.println("Readable: " +f1.canRead());


42
System.out.println("Writable: " +f1.canWrite());

System.out.println("Absolute: " +f1.isAbsolute());

System.out.println("File Size: " +f1.length()+ "bytes");

System.out.println("Is Hidden: " +f1.isHidden());

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:

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 String.getBytes(),FileOutputStream.flush()


,FileOutputStream.close()

Step6:String.getBytes() - returns the bytes array.

Step7:FileOutputStream.flush() - Is used to clear the output steam buffer.

Step8:FileOutputStream.close() - Is used to close output stream (Close the file).

Step9:Stop the program

PROGRAM:

import java.io.*;
import java.io.File;

import java.io.FileOutputStream;

import java.util.Scanner;

public class WriteFile {

public static void main(String args[]) {

final String fileName = "file.txt";

try {

File objFile = new File(fileName);

if (objFile.exists() == false) {

if (objFile.createNewFile()) {

System.out.println("File created successfully.");

44
} else {

System.out.println("File creation failed!!!");

System.exit(0);

//writting data into file

String text;

Scanner SC = new Scanner(System.in);

System.out.println("Enter text to write into file: ");

text = SC.nextLine();

//object of FileOutputStream

FileOutputStream fileOut = new FileOutputStream(objFile);

//convert text into Byte and write into file

fileOut.write(text.getBytes());

fileOut.flush();

fileOut.close();

System.out.println("File saved.");

} catch (Exception Ex) {

System.out.println("Exception : " + Ex.toString());

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:

Write a java program to read content from the file

ALGORITHM:

Step 1: Start the program

Step2: Read the content of the file using FileInputStream

Step3: FileInputStream.read() method which returns an integer value and will read
values until -1 is not found

Step4:Stop the program

PROGRAM:

import java.io.*;
import java.io.File;

import java.io.FileInputStream;

public class ReadFile {

public static void main(String args[]) {

final String fileName = "file.txt";

try {

File objFile = new File(fileName);

if (objFile.exists() == false) {

System.out.println("File does not exist!!!");

System.exit(0);

//reading content from file

String text;

int val;

//object of FileOutputStream

FileInputStream fileIn = new FileInputStream(objFile);

47
//read text from file

System.out.println("Content of the file is: ");

while ((val = fileIn.read()) != -1) {

System.out.print((char) val);

System.out.println();

fileIn.close();

} catch (Exception Ex) {

System.out.println("Exception : " + Ex.toString());

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:

1.Create a class Myclass to implement generic class and generic methods.

2.Get the set of the values belonging to specific data type.

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];

for(int i=1; i < vals.length; i++)

if(vals[i].compareTo(v) < 0)

v = vals[i];

return v;
49
}

public T max()

T v = vals[0];

for(int i=1; i < vals.length;i++)

if(vals[i].compareTo(v) > 0)

v = vals[i];

return v;

class gendemo

public static void main(String args[])

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};

MyClass<Integer> iob = new MyClass<Integer>(inums);

MyClass<Character> cob = new MyClass<Character>(chs);

MyClass<Double>dob = new MyClass<Double>(d);

System.out.println("Max value in inums: " + iob.max());

System.out.println("Min value in inums: " + iob.min());

System.out.println("Max value in chs: " + cob.max());

System.out.println("Min value in chs: " + cob.min());

System.out.println("Max value in chs: " + dob.max());

System.out.println("Min value in chs: " + dob.min());

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:

Write a java program to develop applications using JavaFX controls

ALGORITHM:

Step 1: Creating a Class


Create a Java class and inherit the Application class of the
package javafx.application 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 javafx.scene.
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 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;

public class Registration extends Application {


@Override
public void start(Stage stage) {
//Label for name
Text nameLabel = new Text("Name");

//Text field for name


TextField nameText = new TextField();

//Label for DATE of birth


Text dobLabel = new Text("DATE of birth");

//DATE picker to choose DATE


DATEPicker DATEPicker = new DATEPicker();

//Label for gender


Text genderLabel = new Text("gender");

//Toggle group of radio buttons


ToggleGroup groupGender = new ToggleGroup();
RadioButton maleRadio = new RadioButton("male");
maleRadio.setToggleGroup(groupGender);
RadioButton femaleRadio = new RadioButton("female");
femaleRadio.setToggleGroup(groupGender);

//Label for reservation


Text reservationLabel = new Text("Reservation");

//Toggle button for reservation


ToggleButton Reservation = new ToggleButton();
ToggleButton yes = new ToggleButton("Yes");
ToggleButton no = new ToggleButton("No");
ToggleGroup groupReservation = new ToggleGroup();
yes.setToggleGroup(groupReservation);
no.setToggleGroup(groupReservation);

//Label for technologies known


Text technologiesLabel = new Text("Technologies Known");

//check box for education


CheckBox javaCheckBox = new CheckBox("Java");
javaCheckBox.setIndeterminate(false);

//check box for education


CheckBox dotnetCheckBox = new CheckBox("DotNet");
javaCheckBox.setIndeterminate(false);
53
//Label for education
Text educationLabel = new Text("Educational qualification");

//list View for educational qualification


ObservableList<String> names = FXCollections.observableArrayList(
"Engineering", "MCA", "MBA", "Graduation", "MTECH", "Mphil", "Phd");
ListView<String> educationListView = new ListView<String>(names);

//Label for location


Text locationLabel = new Text("location");

//Choice box for location


ChoiceBox locationchoiceBox = new ChoiceBox();
locationchoiceBox.getItems().addAll
("Hyderabad", "Chennai", "Delhi", "Mumbai", "Vishakhapatnam");

//Label for register


Button buttonRegister = new Button("Register");

//Creating a Grid Pane


GridPane gridPane = new GridPane();

//Setting size for the pane


gridPane.setMinSize(500, 500);

//Setting the padding


gridPane.setPadding(new Insets(10, 10, 10, 10));

//Setting the vertical and horizontal gaps between the columns


gridPane.setVgap(5);
gridPane.setHgap(5);

//Setting the Grid alignment


gridPane.setAlignment(Pos.CENTER);

//Arranging all the nodes in the grid


gridPane.add(nameLabel, 0, 0);
gridPane.add(nameText, 1, 0);

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;");

nameLabel.setStyle("-fx-font: normal bold 15px 'serif' ");


dobLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
genderLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
reservationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
technologiesLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
educationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");
locationLabel.setStyle("-fx-font: normal bold 15px 'serif' ");

//Setting the back ground color


gridPane.setStyle("-fx-background-color: BEIGE;");

//Creating a scene object


Scene scene = new Scene(gridPane);

//Setting title to the Stage


stage.setTitle("Registration Form");

//Adding scene to the stage


stage.setScene(scene);

//Displaying the contents of the stage


stage.show();
}
public static void main(String args[]){
launch(args);
}
}

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:

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
javafx.application 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 javafx.scene.

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 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;

public class ShowFlowPane extends Application {

@Override

public void start(Stage primaryStage) {

FlowPane pane = new FlowPane();

pane.setPadding(new Insets(11, 12, 13, 14));

pane.setHgap(5);

pane.setVgap(5);

// Place nodes in the pane

pane.getChildren().addAll(new Label("First Name:"),

new TextField(), new Label("MI:"));

TextField tfMi = new TextField();

tfMi.setPrefColumnCount(1);

pane.getChildren().addAll(tfMi, new Label("Last Name:"),

new TextField());

// Create a scene and place it in the stage

Scene scene = new Scene(pane, 210, 150);

primaryStage.setTitle("ShowFlowPane");

primaryStage.setScene(scene); // Place the scene in the stage

primaryStage.show(); // Display the stage

public static void main(String[] args) {

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:

To develop a java applications using JavaFX menus

ALGORITHM:

Step 1:Start the program

Step 2: JavaFX provides five classes that implement menus: MenuBar, Menu,
MenuItem, CheckMenuItem, and RadioButtonMenuItem.

Step 3: MenuBar is a top-level menu component used to hold the menus.

Step 4: A menu consists of menu items that the user can select (or toggle on or off).

Step 5: A menu item can be an instance of MenuItem, CheckMenuItem, or


RadioButtonMenuItem.

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

has been implemented using JavaFX and executed successfully.

62
EX.NO:11 SCIENTIFIC CALCULATOR
DATE:

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 Double.parseDouble 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 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:

public class StringExample {


public static void main(String[] args){
String s1="Computer Science";
int x=307;
String s2=s1+" "+x;
String s3=s2.substring(10,17);
String s4="is fun";
String s5=s2+s4;
System.out.println("s1:"+s1);
System.out.println("s2:"+s2);
System.out.println("s3:"+s3);
System.out.println("s4:"+s4);
System.out.println("s5:"+s5);
x=3;
int y=5;
String s6=x+y+"total";
String s7="total"+x+y;
String s8=" "+x+y+"total";
System.out.println("s6:"+s6);
System.out.println("s7:"+s7);
System.out.println("s8:"+s8);
}
}

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

You might also like