0% found this document useful (0 votes)
51 views40 pages

S Lab Record

Ops

Uploaded by

unmaxcoc1
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)
51 views40 pages

S Lab Record

Ops

Uploaded by

unmaxcoc1
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/ 40

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

II YEAR B.E. – 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______________ CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY

during the academic year_________________________.

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

Date: Internal:

External:
Vision of Institution
To build Jeppiaar Engineering College as an Institution of Academic Excellence in Technical
education and Management education and to become a World Class University.
Mission of Institution
M1 To excel in teaching and learning, research and innovation by promoting the principles of
scientific analysis and creative thinking

To participate in the production, development and dissemination of knowledge and interact


M2 with national and international communities
To equip students with values, ethics and life skills needed to enrich their lives and enable them
M3 to meaningfully contribute to the progress of society
To prepare students for higher studies and lifelong learning, enrich them with the practical and
M4 entrepreneurial skills necessary to excel as future professionals and contribute to Nation’s
economy

Program Outcomes (POs)


Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and
PO3 design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
PO10 engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

1 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


Project management and finance: Demonstrate knowledge and understanding of the
PO11 engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

Program Educational Objectives (PEOs)


PEO1 Apply their technical competence in computer science to solve real world problems, with technical
and people leadership.
PEO2 Conduct cutting edge research and develop solutions on problems of social relevance.

PEO3 Work in a business environment, exhibiting team skills, work ethics, adaptability and lifelong
learning.

Program Specific Outcomes (PSOs)


Students will be able to

PSO1 Exhibit design and programming skills to build and automate business solutions using cutting edge
technologies.

PSO2 Strong theoretical foundation leading to excellence and excitement towards research, to provide
elegant solutions to complex problems.

PSO3 Ability to work effectively with various engineering fields as a team to design, build and develop
system applications

COURSE OUTCOMES:

CO1 Design and develop java programs using object oriented programming concepts

CO2 Develop simple applications using object oriented concepts such as package, exceptions

CO3 Implement multithreading, and generics concepts


CO4 Create GUIs and event driven programming applications for real world problems

CO5 Implement and deploy web applications using Java

2 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

3 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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 “Linear_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 there
is 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

4 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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 point
to 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 linear search
public static int search(int arr[], int x)
{
int n = arr.length;
// Traverse array arr[]
for (int i = 0; i < n; i++) {

5 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

6 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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;

7 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

8 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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.

9 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

10 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

11 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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)

12 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

13 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

14 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

15 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

16 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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.

17 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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 as
circle’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();
}

18 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

19 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

20 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


OUTPUT

RESULT

Thus, above program executed and output is verified.

21 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

22 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


OUTPUT:

RESULT

Thus, above program executed and output is verified.

23 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

24 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

25 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


A a=new A("one");
a.start();
}
}

OUTPUT:

RESULT

Thus, above program executed and output is verified.

26 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

27 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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.

28 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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>("JEC", 3108);

29 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


obj.print();
}
}

OUTPUT

JEC

3108

RESULT

Thus, above program executed and output is verified.

30 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

31 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

32 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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.

33 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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;

34 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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;

35 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


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

36 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


gc.fillRect(playerOneXPos, playerOneYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
}
// start the application
public static void main(String[] args) {
launch(args);
}
}

OUTPUT

37 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY


RESULT
Thus, the mini project using Java concepts was developed and executed successfully.

38 DEPT OF CSE / CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY

You might also like