0% found this document useful (0 votes)
31 views47 pages

Oops Manual

Ooos manual

Uploaded by

no1542845
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)
31 views47 pages

Oops Manual

Ooos manual

Uploaded by

no1542845
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/ 47

DEPARTMENT OF COMPUTER SCIENCE AND

ENGINEERING

LAB MANUAL
CS3381-OBJECT ORIENTED PROGRAMMING LABORATORY

YEAR - 2024 – 2025 [ODD SEM]

YEAR / SEMESTER: II/III


DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

CS3381 OBJECT ORIENTED PROGRAMMING

LABORATORY

YEAR - 2024 – 2025 [ODD SEM]

YEAR / SEMESTER: II / III

NAME & DESIGNATION SIGNATURE WITH DATE

PREPARED BY

VERIFIED BY

APPROVED BY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

II YEAR B.E.CSE – III SEM

ACADEMIC YEAR (2024 -25 ODD SEM)

Name :

Register Number :

Subject Name :

Subject Code :

Batch :
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

This is a Bonafide Record Work of

Register No submitted for the Anna University Practical

Examination held on CS3351 OBJECT ORIENTED PROGRAMMING LABORATORY

during the academic year .

Signature of the Lab-In-Charge Signature of the HOD

Date: Internal:

External:
INDEX

Ex.No DATE TITLE PAGE NO. SIGNATURE

Sequential search, binary search, and


01
quadratic sorting algorithms

Stack and queue data structures using


02
classes and objects

03 Generation pay-slips for the employees

Illustration of Abstract Class &


04
Interface
Implementation of user defined
05 exception.

06 Illustration of multi-threading

07 Displaying file information

Demonstrate the features of generics


08
classes

09 Javafx controls, layouts and menu

Develop a mini project for any


10
application using Java concepts
11
Appedix
REQUIREMENTS

Windows 10
Java SE 12
Ex No: 1 PROGRAM TO SEQUENTIAL SEARCH, BINARY SEARCH,
AND QUADRATIC SORTING ALGORITHMS
Date:

AIM:

To develop a Java application to Sequential search, Binary search and quadratic sorting algorithms.

ALGORITHM:

STEP 1: Start

STEP 2: Define Sub function “Sequential_Search()”

STEP 2.1: First, we have to traverse the array elements using a for loop.

STEP 2.2: In each iteration of for loop, compare the search element with the current array element,

STEP 2.2.1: If the element matches, then return the index of the corresponding array element

STEP 2.2.2: If the element does not match, then move to the next element.

STEP 2.2.3: If thereis no match or the search element is not present in the given array, return -1

STEP 3: Define Sub function “Binary_Search()”

STEP 3.1: A ← sorted array

STEP 3.2: n ← size of array

STEP 3.3:x ← value to be searched

STEP 3.4: Set lowerBound = 1

STEP 3.5: Set upperBound = n

STEP 3.6: while x not found

STEP 3.7: if upperBound < lowerBound

STEP 3.8: EXIT: x does not exist.

STEP 3.9: set midPoint = lowerBound + (upperBound - lowerBound) / 2

STEP 3.10: if A[midPoint] < x

STEP 3.11: set lowerBound = midPoint + 1


STEP 3.12: if A[midPoint] > x

STEP 3.11: set upperBound = midPoint - 1 Step 3.12: if A[midPoint] = x

STEP 3.13: EXIT: x found at location midPoint

STEP 3.14: end while

STEP 3.15: end procedure

STEP 4: Define Sub function “Selection_Sort()”

STEP 4.1: Set Min to location 0 in Step 1.

STEP 4.2: Look for the smallest element on the list.

STEP 4.3: Replace the value at location Min with a different value. Step 4.4: Increase Min to pointto
the next element

STEP 4.5: Continue until the list is sorted

STEP 5: Define Sub function “Insertion_Sort()”

STEP 5.1: Iterate through the array from arr[1] to arr[n].

STEP 5.2: Compare the current element (key) to one that came before it.

STEP 5.3: If the data at the current index is less than the data at the previous index, you will
compare it to the element before it

STEP 5.4: You will shift bigger elements to the next index to make space for swapped elements, and
then you will iterate the same steps again to sort the complete array.

STEP 6: Call the function

STEP 7: Stop

PROGRAM:

Sequential Search:
class Sequential_Search
{
// Function for search
public static int search(int arr[], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++)
{
// If element found then
// return that index
if (arr[i] == x)
return i;
}
return -1;
}
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 2, 3, 4, 10, 40 };

// Element to search
int x = 10;
// Function Call
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present" + " at index " + result);
}
}

Binary Search:
class BinarySearch {
// Function that returns index of
// x if it is present in arr[l, r]
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
// If the element is present
// at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than
// mid, then it can only be
// present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l,mid - 1, x);
// Else the element can only be
// present in right subarray
return binarySearch(arr, mid + 1,r, x);
}
// Reach here when element is
// not present in array
return -1;
}
// Driver Code
public static void main(String args[])
{
// Create object of this class
BinarySearch ob = new BinarySearch();
// Given array arr[]
int arr[] = { 2, 3, 4, 10, 40 };
int n = arr.length;
int x = 10;
// Function Call
int result = ob.binarySearch(arr, 0,n - 1, x);
if (result == -1)
System.out.println("Element "+ "not present");
else
System.out.println("Element found"+ " at index "+ result);
}
}

Selection Sort:

class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

Insertion Sort

// Java program for implementation of Insertion Sort


class InsertionSort
{
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
/* A utility function to print array of size n*/
static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
InsertionSort ob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
}

OUTPUT:
Sequential Search
Element is present at index 4
Binary Search
Element is present at index 4
Selection Sort
Sorted Array 11 12 22 25 64
Insertion Sort
5 6 11 12 13

RESULT

Thus, above program was executed and output is verified.


Ex No: 2 PROGRAM TO DEVELOP STACK AND QUEUE DATA
STRUCTURES USING CLASSES AND OBJECTS
Date:

AIM:

To develop a stack and queue data structures using classes and objects.

ALGORITHM:

STEP 1: Push inserts an item at the top of the stack (i.e., above its current top element).
STEP 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.
STEP 3: IsEmpty tests if the stack is empty or not.
STEP 4: IsFull tests if the stack is full or not.
STEP 5: Peek returns the object at the top of the stack without removing it from the stack
ormodifying the stack in any way.
STEP 6: Size returns the total number of elements present in the stack.
PROGRAM:

Stack Implementation

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())
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
// Utility function to pop a top element from the stack
public int pop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
System.out.println("Removing " + peek());

// decrease stack size by 1 and (optionally) return the popped element


return arr[top--];
}
// Utility function to return the top element of the stack
public int peek()
{
if (!isEmpty())
{
return arr[top];
}
else
{
System.exit(-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);
stack.push(1); // inserting 1 in the stack
stack.push(2); // inserting 2 in the stack
stack.pop(); // removing the top element (2)
stack.pop(); // removing the top element (1)
stack.push(3); // inserting 3 in the stack
System.out.println("The top element is " + stack.peek());
System.out.println("The stack size is " + stack.size());
stack.pop(); // removing the top element (3)
// check if the stack is empty
if (stack.isEmpty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}

OUTPUT

Inserting 1

Inserting 2

Removing 2

Removing 1

Inserting 3

The top element is 3

The stack size is 1

Removing 3

The stack is empty

Queue Implementation
import java.util.LinkedList;
import java.util.Queue;
class Main
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<String>();
queue.add("A"); // Insert `A` into the queue
queue.add("B"); // Insert `B` into the queue
queue.add("C"); // Insert `C` into the queue
queue.add("D"); // Insert `D` into the queue
// Prints the front of the queue (`A`)
System.out.println("The front element is " + queue.peek());
queue.remove(); // removing the front element (`A`)
queue.remove(); // removing the front element (`B`)
// Prints the front of the queue (`C`)
System.out.println("The front element is " + queue.peek());
// Returns the total number of elements present in the queue
System.out.println("The queue size is " + queue.size());
// check if the queue is empty
if (queue.isEmpty())
{
System.out.println("The queue is empty");
}
else
{
System.out.println("The queue is not empty");
}
}
}

OUTPUT
The front element is A
The front element is C
The queue size is 2
The queue is not empty

RESULT

Thus, above program executed and output is verified.


Ex No: 3

PROGRAM TO GENERATE PAYSLIP USING INHERITANCE


Date:

AIM

To develop a java application to generate pay slip for different category of employees using the
concept of inheritance.

EXPLANATION
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. Add Basic Pay (BP) as the member of all the inherited classes
with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund.
Generate pay slips for the employees with their gross and net salary

ALGORITHM

STEP 1: Create the specified classes


STEP 2: Add members of the inherited class
STEP 3: Calculate gross salary and net salary with the given equation
STEP 4: Display the pay slip with net salary and gross salary

PROGRAM
package employee;
import java.io.IOException;
import java.util.Scanner;
class Emp
{
String ename,Address,email;
int eid;
int mobile;
void getEmployeedetails()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the Emp_id. :");
eid=in.nextInt();
System.out.println("Enter the Employee Name:");
ename=in.next();
System.out.println("Enter the Employee Address:");
Address=in.next();
System.out.println("Enter the Employee Email id :");
email=in.next();
System.out.println("Enter the Mobile No:");
mobile=in.nextInt();
}
void pay_calulation(double BasicPay)
{
double DA,HRA,PF,Sfund,Gross_Salary,Netsalary;
DA=BasicPay*0.97;
HRA=BasicPay*0.10;
PF=BasicPay*0.12;
Sfund=BasicPay*0.1;
Gross_Salary=BasicPay+DA+HRA;
Netsalary=Gross_Salary-(PF+Sfund);
System.out.println("Gross salary of the Employee"+Gross_Salary);
System.out.println("Net salary of the Employee: "+Netsalary);
}
void display()
{
System.out.println("Emp_id:"+eid);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Address:"+Address);
System.out.println("Employee Email id :"+email);
System.out.println("Employee Mobile No:"+mobile);
}
}
class Programmer extends Emp
{
double BasicPay;
void Programmerdetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Programmer:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssistantProfessor extends Emp
{
void APDetails()
{
double BasicPay;
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssistantProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class AssociateProfessor extends Emp
{
double BasicPay;
void ASPDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the AssociateProfessor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}
}
class Professor extends Emp
{
double BasicPay;
void profDetails()
{
getEmployeedetails();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Basic Pay of the Professor:");
BasicPay=in.nextInt();
display();
pay_calulation(BasicPay);
}

}
public class Employee
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Choose the type Employee");
System.out.println("1.Programmer ,2.Assistant Professor,3.Associate Professor ,4.Professor: ");
int ch=in.nextInt();
switch(ch)
{
case 1: System.out.println("PROGRAMMER DETAILS");
Programmer p=new Programmer();
p.Programmerdetails();
break;
case 2: System.out.println("Assistant Professor DETAILS");
AssistantProfessor ap=new AssistantProfessor();
ap.APDetails();
break;
case 3: System.out.println("Associate Professor DETAILS");
AssociateProfessor asp=new AssociateProfessor();
asp.ASPDetails();
break;
case 4: System.out.println("Professor DETAILS");
Professor pf=new Professor();
pf.profDetails();
break;
}
}
}

OUTPUT

RESULT

Thus, above program executed and output is verified.


Ex No: 4 PROGRAM TO CALCULATE AREA USING
ABSTRACT CLASS &INTERFACE
Date:

AIM

To write a java program to calculate the area of rectangle, circle and triangle using the concept
of abstract class.

EXPLANATION
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.
ALGORITHM
STEP 1: Create an abstract class with the name shape
STEP 1.1: Let sides of shape be Side1 and Side2, create variables Side1, Side2
STEP 1.2: Define an empty method PrintArea()
STEP 2: Create three classes with names Rectangle, Triangle and Circle
STEP 2.1: Extend the Shape class in each of these classes
STEP 2.2: Develop the implementation of Area in each class appropriately
STEP 2.3: For Eg: PrintArea() of Circle would be 3.14*Side1*Side1 ; here Side1 is
considered ascircle’s radius
STEP 3: Write a class with main method
STEP 4: Create instance of all three classes
STEP 5: Calculate the Area for each shape
STEP 6: Display the area

PROGRAM

Using abstract class:


package javaapplication3;
abstract class shape
{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
@Override
public void print_area()
{
area_rect=a*b;
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
int area_tri;
@Override
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area oftriangle is:"+area_tri);
}
}
class circle extends shape
{
int area_circle;
@Override
public void print_area()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area ofcircle is:"+area_circle);
}
}
public class JavaApplication3 {
public static void main(String[] args) {
rectangle r=new rectangle();
r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();
}
}
Using Interface:
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;
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
{
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
obj.input();
obj.area();
}
}
OUTPUT

RESULT

Thus, above program executed and output is verified.


Ex No: 5 PROGRAM TO IMPLEMENT USER DEFINED EXCEPTION
HANDLING
Date:

AIM

To write a java program to implement user defined exception handling

ALGORITHM

STEP 1: Create a class that extends Exception class


STEP 1.1: Let the name be MyException
STEP 1.2: Define a constructor that calls super()
STEP 2: Create a class with main method
STEP 2.1: Use the MyException in the try catch clause

PROGRAM

package example1;
class MyException extends Exception
{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("MyException Occurred: "+str1);
}
}
public class Example1
{
public static void main(String[] args)
{
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block");
System.out.println(exp);
}
}
}
OUTPUT:

RESULT

Thus, above program executed and output is verified.


Ex No: 6

PROGRAM TO IMPLEMENT MULTITHREADED APPLICATION


Date:

AIM

To write a java program that implements a multi-threaded application.

EXPLANATION
Write a java program that implements a multi-threaded application that has three threads.
First thread generates a random integer every 1 second and if the value is even, second thread
computes the square of the number and prints. If the value is odd, the third thread will print the value
of cube of the number.
ALGORITHM

STEP 1: Create three classes, IntThread, SqThread, CubeThread


STEP 1.1: Let the classes extend the Thread Class
STEP 1.2: Let the run method of IntTheadhave random no generator
STEP 1.3: Let the run method of SqThread have square generator
STEP 1.4: Let the run method of CubeThread have cube generator
STEP 2: Create a class with main method
STEP 2.1: Create instances of IntThread, SqThread, CubeThread
STEP 2.2: Synchronize all the threads and print no, then square and then cube

PROGRAM
package mtherad;
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{this.x=x;
}
@Override
public void run()
{
System.out.println("Thread Name:Even Thread and square is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x){
this.x=x;
}
@Override
public void run()
{
System.out.println("Thread Name:Odd Thread and cube is :"+ x * x * x);
}
}
class A extends Thread{
public String tname;
public Random r;
public Thread t1,t2;
public A(String s){
tname=s;
}
@Override
public void run()
{
int num=0;
r=new Random();
try {
for(int i=0;i<50;i++){
num=r.nextInt(100);
System.out.println("main thread and generated number is"+num);
if(num%2==0)
{
t1=new Thread(new even(num));
t1.start();
}else{
t2=new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
}
public class Mtherad
{
public static void main(String[] args)
{
A a=new A("one");
a.start();
}
}

OUTPUT:

RESULT

Thus, above program executed and output is verified.


Ex No: 7

PROGRAM FOR DISPLAYING FILE INFORMATION


Date:

AIM

To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.

EXPLANATION

Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.
ALGORITHM
STEP 1: Create a text file with some contents
STEP 1.1: Let the name of file be ‘Example.txt’
STEP 1.2: Enter some content and save in the same folder as java program
STEP 2: Create a class with main method
STEP 2.1: Create a file object
STEP 2.2: Print all the attributes of the file objects
PROGRAM
package Filedemo;
import java.util.Scanner;
import java.io.File;
public class Filedemo {
public static void main(String[] args)
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("*****************");
System.out.println("FILE INFORMATION");
System.out.println("*****************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());

}
}

OUTPUT

RESULT

Thus, above program executed and output is verified.


Ex No: 8 DEVELOP APPLICATIONS TO DEMONSTRATE THE FEATURES OF
GENERICS CLASSES
Date:

AIM

To develop applications to demonstrate the features of generics classes

ALGORITHM

STEP 1: To create an instance of generic class


STEP 2: BaseType <Type> obj = new BaseType <Type>()
STEP 3: We use < > to specify Parameter type
STEP 4: An object of type T is declared

PROGRAM

// Java program to show multiple


// type parameters in Java Generics
// We use < > to specify Parameter type
class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
// To print objects of T and U
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
// Driver class to test above
class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj = new Test<String, Integer>("AGNI", 3128);
obj.print();
}
}

OUTPUT

AGNI

3128

RESULT

Thus, above program executed and output is verified.


Ex No: 9
JAVA FX CONTROLS, LAYOUTS AND MENU

Date:

AIM

To develop an application using JavaFX controls, layouts and menus.

ALGORITHM

STEP 1: Start the EclipseIDE


STEP 2: Goto File -> new -> Java Project.
STEP 3: Create class under src directory
STEP 4: Select the menu item File -> New -> Class
STEP 5: Add external Jar files which supports javafx
STEP 6: Extend javafx.application.Application and override start()
STEP 7: Create a Layouts and add MenuBar to it
STEP 8: Create a Scene
STEP 9: Prepare the Stage
STEP 10: Create an event for the MenuItem
STEP 11: Call the launch () method to run the application
STEP 12: Stop the program

PROGRAM

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Label_Test extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
BorderPane BPane = new BorderPane();
BPane.setTop(new Label("This will be at the top"));
BPane.setLeft(new Label("This will be at the left"));
BPane.setRight(new Label("This will be at the Right"));
BPane.setCenter(new Label("This will be at the Centre"));
BPane.setBottom(new Label("This will be at the bottom"));
Scene scene = new Scene(BPane,600,400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}

OUTPUT

Menu
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenuExample extends Application {
public static void main(String[] args)
{
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception
{
// TODO Auto-generated method stub
BorderPane root = new BorderPane();
Scene scene = new Scene(root,200,300);
MenuBar menubar = new MenuBar();
Menu FileMenu = new Menu("File");
MenuItem filemenu1=new MenuItem("new");
MenuItem filemenu2=new MenuItem("Save");
MenuItem filemenu3=new MenuItem("Exit");
Menu EditMenu=new Menu("Edit");
MenuItem EditMenu1=new MenuItem("Cut");
MenuItem EditMenu2=new MenuItem("Copy");
MenuItem EditMenu3=new MenuItem("Paste");
EditMenu.getItems().addAll(EditMenu1,EditMenu2,EditMenu3);
root.setTop(menubar);
FileMenu.getItems().addAll(filemenu1,filemenu2,filemenu3);
menubar.getMenus().addAll(FileMenu,EditMenu);
primaryStage.setScene(scene);
primaryStage.show();

}
}

OUTPUT

RESULT

Thus, above program executed and output is verified.


Ex No: 10
DEVELOP A MINI PROJECT FOR ANY APPLICATION
Date: USING JAVA CONCEPTS

AIM

To develop a mini project for Ping Pong game application using JavaFX controls, layouts.

ALGORITHM

STEP 1: Start the EclipseIDE


STEP 2: Goto File -> new -> Java Project.
STEP 3: Create class under src directory
STEP 4: Select the menu item File -> New -> Class
STEP 5: Add external Jar files which supports javafx
STEP 6: Extend javafx.application.Application and override start()
STEP 7: Create a Layouts and add Shapes to it
STEP 8: Create a Scene
STEP 9: Prepare the Stage
STEP 10: Create a Mouse event for the shapes
STEP 11: Call the launch () method to run the application
STEP 12: Stop the program

PROGRAM
import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Ex11 extends Application
{
//variable
private static final int width = 800;
private static final int height = 600;
private static final int PLAYER_HEIGHT = 100;
private static final int PLAYER_WIDTH = 15;
private static final double BALL_R = 15;
private int ballYSpeed = 1;
private int ballXSpeed = 1;
private double playerOneYPos = height / 2;
private double playerTwoYPos = height / 2;
private double ballXPos = width / 2;
private double ballYPos = height / 2;
private int scoreP1 = 0;
private int scoreP2 = 0;
private boolean gameStarted;
private int playerOneXPos = 0;
private double playerTwoXPos = width - PLAYER_WIDTH;
public void start(Stage stage) throws Exception
{
stage.setTitle("P O N G");
//background size
Canvas canvas = new Canvas(width, height);
GraphicsContext gc = canvas.getGraphicsContext2D();
//JavaFX Timeline = free form animation defined by KeyFrames and their duration
Timeline tl = new Timeline(new KeyFrame(Duration.millis(10), e -> run(gc)));
//number of cycles in animation INDEFINITE = repeat indefinitely
tl.setCycleCount(Timeline.INDEFINITE);
//mouse control (move and click)
canvas.setOnMouseMoved(e -> playerOneYPos = e.getY());
canvas.setOnMouseClicked(e -> gameStarted = true);
stage.setScene(new Scene(new StackPane(canvas)));
stage.show();
tl.play();
}
private void run(GraphicsContext gc)
{
//set graphics
//set background color
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, width, height);
//set text
gc.setFill(Color.BLACK);
gc.setFont(Font.font(25));
if(gameStarted) {
//set ball movement
ballXPos+=ballXSpeed;
ballYPos+=ballYSpeed;
//simple computer opponent who is following the ball
if(ballXPos < width - width / 4)
{
playerTwoYPos = ballYPos - PLAYER_HEIGHT / 2;
} else
{
playerTwoYPos = ballYPos > playerTwoYPos + PLAYER_HEIGHT / 2 ?playerTwoYPos += 1:
playerTwoYPos - 1;
}
//draw the ball
gc.fillOval(ballXPos, ballYPos, BALL_R, BALL_R);
} else
{
//set the start text
gc.setStroke(Color.BLACK);
gc.setTextAlign(TextAlignment.CENTER);
gc.strokeText("Click", width / 2, height / 2);
//reset the ball start position
ballXPos = width / 2;
ballYPos = height / 2;
//reset the ball speed and the direction
ballXSpeed = new Random().nextInt(2) == 0 ? 1: -1;
ballYSpeed = new Random().nextInt(2) == 0 ? 1: -1;
}
//makes sure the ball stays in the canvas
if(ballYPos > height || ballYPos < 0) ballYSpeed *=-1;
//if you miss the ball, computer gets a point
if(ballXPos < playerOneXPos - PLAYER_WIDTH)
{
scoreP2++;
gameStarted = false;
}
//if the computer misses the ball, you get a point
if(ballXPos > playerTwoXPos + PLAYER_WIDTH)
{
scoreP1++;
gameStarted = false;
}
//increase the speed after the ball hits the player
if( ((ballXPos + BALL_R > playerTwoXPos) && ballYPos >= playerTwoYPos && ballYPos <=
playerTwoYPos + PLAYER_HEIGHT) ||
((ballXPos < playerOneXPos + PLAYER_WIDTH) && ballYPos >= playerOneYPos &&
ballYPos <= playerOneYPos + PLAYER_HEIGHT))
{
ballYSpeed += 1 * Math.signum(ballYSpeed);
ballXSpeed += 1 * Math.signum(ballXSpeed);
ballXSpeed *= -1;
ballYSpeed *= -1;
}
//draw score
gc.fillText(scoreP1 + "\t\t\t\t\t\t\t\t" + scoreP2, width / 2, 100);
//draw player 1 & 2
gc.fillRect(playerTwoXPos, playerTwoYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
gc.fillRect(playerOneXPos, playerOneYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
}
// start the application
public static void main(String[] args) {
launch(args);
}
}

OUTPUT
RESULT
Thus, the mini project using Java concepts was developed and executed successfully.
1.1Linear search
It is used to search a key element from multiple elements.

o Traverse(travel) the array


o Match the key element with array element
o If key element is found, return the index position of the array element
o If key element is not found, return -1

1.2Binary search

A search algorithm that finds the position of a target value within a sorted
array. Binary search compares the target value to the middle element of
the array.

Steps
 Divide the search space into two halves by finding the middle index
“mid”.
 Compare the middle element of the search space with the key.
 If the key is found at middle element, the process is terminated.
 If the key is not found at middle element, choose which half will be used as
the next search space.
o If the key is smaller than the middle element, then the left side is
used for next search.
o If the key is larger than the middle element, then the right side is
used for next search.
 This process is continued until the key is found or the total search space is
exhausted.
1.3Selection Sort
In selection sort, the smallest value
among the unsorted elements of the array is
selected in every pass and inserted to its appropriate
position into the array.
1.4Insertion Sort

Initial:
Current element is 23
The first element in the array is assumed to be sorted.
The sorted part until 0th index is : [23]

First Pass:
Compare 1 with 23 (current element with the sorted part).
Since 1 is smaller, insert 1 before 23 .
The sorted part until 1st index is: [1, 23]

Second Pass:
Compare 10 with 1 and 23 (current element with the sorted part).
Since 10 is greater than 1 and smaller than 23 ,
insert 10 between 1 and 23 .
The sorted part until 2nd index is: [1, 10, 23]

Third Pass:
Compare 5 with 1 , 10 , and 23 (current element with the sorted part).
Since 5 is greater than 1 and smaller than 10 , insert 5 between 1 and 10
The sorted part until 3rd index is : [1, 5, 10, 23]

Fourth Pass:
Compare 2 with 1, 5, 10 , and 23 (current element with the sorted part).
Since 2 is greater than 1 and smaller than 5 insert 2 between 1 and 5 .
The sorted part until 4th index is: [1, 2, 5, 10, 23]

Final Array:
The sorted array is: [1, 2, 5, 10, 23]

2.1. Stack Implementation

The stack data structure is a linear data structure that accompanies a


principle known as LIFO (Last In First Out) or FILO (First In Last Out).
Real-life examples of a stack are a deck of cards, piles of books, piles of
money, and many more.

In array implementation, the stack is formed using an array. All the


operations are performed using arrays. You will see how all operations
can be implemented on the stack in data structures using an array data
structure

In order to make manipulations in a stack, there are certain operations


provided to us for Stack, which include:

push() to insert an element into the stack


pop() to remove an element from the stack
top() Returns the top element of the stack.
isEmpty() returns true if the stack is empty else false.
size() returns the size of the stack.

2.1 Queue implementation

A queue is a linear data structure that stores the elements sequentially. It


uses the FIFO (First In First Out) approach for accessing elements.
Queues are typically used to manage threads in multithreading and
implementing priority queuing systems.

Basic Operations of Queue

Enqueue (Insert): Adds an element to the rear of the queue.


Dequeue (Delete): Removes and returns the element from the front of
the queue.
Peek: Returns the element at the front of the queue without removing it.
Empty: Checks if the queue is empty.
Full: Checks if the queue is full.

To implement a queue

Create an array ar of size n and take two variables front and rear which
are initialized as 0 and -1 respectively
Rear is the index up to which the elements are stored in the array
including the rear index itself. We mainly add an item by incrementing
it.

Front is the index of the first element of the array. We mainly remove
the element at this index in Dequeue operation.

You might also like