Oopj Meet
Oopj Meet
BACHELOR OF TECHNOLOGY
III SEMESTER
Laboratory Manual
Session:2024-25
OBJECT ORIENTED PROGRAMMING PRACTICAL BOOK
COMPUTER SCIENCE &ENGINEERING DEPARTMENT
PREFACE
It gives us immense pleasure to present the first edition of the OBJECT ORIENTED
PROGRAMMING Practical Book for the B.Tech . 3rd semester students for PARUL
UNIVERSITY.
The OOP theory and laboratory courses at PARUL UNIVERSITY, WAGHODIA,
VADODARA are designed in such a way that students develop the basic understanding of the
subject in the theory classes and then try their hands on the experiments to realize the various
implementations of problems learnt during the theoretical sessions. The main objective of the
OOP laboratory course is: Learning OOP through Experimentations. All the experiments are
designed to illustrate various problems in different areas of OOP and also to expose the students
to various uses.
The objective of this OOP Practical Book is to provide a comprehensive source for all
the experiments included in the OOP laboratory course. It explains all the aspects related to
every experiment such as: basic underlying concept and how to analyze a problem. It also gives
sufficient information on how to interpret and discuss the obtained results.
We acknowledge the authors and publishers of all the books which we have consulted
while developing this Practical book. Hopefully this OOP Practical Book will serve the purpose
for which it has been developed.
INSTRUCTIONS TO STUDENTS
1. The main objective of the OOP laboratory is: Learning through the Experimentation. All
the experiments are designed to illustrate various problems in different areas of OOP and
also to expose the students to various problems and their uses.
2. Be prompt in arriving to the laboratory and always come well prepared for the practical.
3. Every student should have his/her individual copy of the OOP Practical Book.
4. Every student have to prepare the notebooks specifically reserved for the OOP practical
work: ” OOP Practical Book”
5. Every student has to necessarily bring his/her OOP Practical Book, OOP Practical Class
Notebook and OOP Practical Final Notebook.
6. Finally find the output of the experiments along with the problem and note results in the
OOP Practical Notebook.
7. The grades for the OOP practical course work will be awarded based on our performance
in the laboratory, regularity, recording of experiments in the OOP Practical Final
Notebook, lab quiz, regular viva-voce and end-term examination.
CERTIFICATE
Mr./Ms.............................................................................................................
Head Of Department:...........................................
TABLE OF CONTENT
1
2403031267030 OOPJ Laboratory
Practical-1
Output:-
2
Practical-2
3
2403031267030 OOPJ Laboratory
Practical-2
// Perform addition, subtraction, multiplication, division, and modulo operations on 'a' and 'b'.
int A = a + b;
System.out.println("Addition: " + A);
int S = a - b;
System.out.println("Subtraction: " + S);
int M = a * b;
System.out.println("Multiplication: " + M);
int D = a / b;
System.out.println("Division: " + D);
int R = a % b;
System.out.println("Remainder: " + R);
// Bitwise Operations
int x = 12; // 1100 in Binary
int y = 6; // 0110 in Binary
}
}
Output:-
5
Practical-3
6
2403031267030 OOPJ Laboratory
Practical-3
8
2403031267030 OOPJ Laboratory
9
Practical-4
10
2403031267030 OOPJ Laboratory
Practical-4
// Prompt the user to enter the employee's name and read it as a string.
System.out.print("Enter employee name: ");
name = scanner.nextLine();
// Prompt the user to enter the employee's age and read it as an integer.
System.out.print("Enter employee age: ");
age = scanner.nextInt();
// Prompt the user to enter the employee's salary and read it as a double.
System.out.print("Enter employee salary: ");
salary = scanner.nextDouble();
}
11
2403031267030 OOPJ Laboratory
12
Practical-5
13
2403031267030 OOPJ Laboratory
Practical-5
Aim:- Write a Java program that prints all real solutions to the quadratic
equation ax2 + bx+c = 0. Read in a, b, c and use the quadratic formula. If
the discriminate b2-4ac is negative, display a message stating that
there are no real solutions?
Code:-
// Import the Scanner class from the java.util package to read user input.
import java.util.Scanner;
// Main class that contains the program's entry point.
public class Main {
public static void main(String[] args) {
// Print a message to the console.
System.out.println("Prince_Chhodavadiya");
// Create a Scanner object to read user input.
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter coefficients a, b, and c for a quadratic equation.
System.out.print("Enter the coefficient a: ");
double a = scanner.nextDouble();
14
2403031267030 OOPJ Laboratory
15
2403031267030 OOPJ Laboratory
}
}
Output:-
16
Practical-6
17
2403031267030 OOPJ Laboratory
Practical-6
Aim:- The Fibonacci sequence is defined by the following rule. The first
2 values in the sequence are 1, 1. Every subsequent value is the sum of
the 2 values preceding it. Write a Java program that uses both recursive
and non- recursive functions to print the nth value of the Fibonacci
sequence?
Code:-
// Import the Scanner class from the java.util package to read user input.
import java.util.Scanner;
// Main class that contains the program's entry point. public class Main {
// Recursive function to calculate the nth Fibonacci number
public static int recursiveFibonacci(int n) {
// Base case: If n is 0 or 1, return n.
if (n <= 1) {
return n;
}
// Recursive step: Calculate Fibonacci(n-1) + Fibonacci(n-2).
return recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2);
}
// Non-recursive function to calculate the nth Fibonacci number public static int
nonRecursiveFibonacci(int n) {
// Base case: If n is 0 or 1, return n.
if (n <= 1) {
return n;
}
// Initialize variables to store the previous two Fibonacci numbers.
int prev1 = 1;
int prev2 = 1;
int fib = 0;
18
2403031267030 OOPJ Laboratory
// Calculate the nth Fibonacci number using both recursive and non-recursive methods.
int recursiveResult = recursiveFibonacci(n);
int nonRecursiveResult = nonRecursiveFibonacci(n);
19
Practical-7
20
2403031267030 OOPJ Laboratory
Practical-6
Aim:- Write a Java program that prompts the user for an integer and
then prints out all the prime numbers up to that Integer?
Code:-
import java.util.Scanner;
public class Main {
// Function to check if a number is prime
public static boolean isPrime(int num) {
// Check if the number is less than or equal to 1; such numbers are not prime.
if (num <= 1) {
return false;
}
// Check if the number is 2 or 3; they are prime.
if (num <= 3) {
return true;
}
// Check if the number is divisible by 2 or 3; if yes, it's not prime.
if (num % 2 == 0 || num % 3 == 0) {
return false;
}
// Check for prime numbers using the 6k +/- 1 rule.
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// Print a message to the console.
System.out.println("Prince_Chhodavadiya");
21
2403031267030 OOPJ Laboratory
}
}
}
}
Output:-
22
Practical-8
23
2403031267030 OOPJ Laboratory
Practical-8
// Prompt the user to enter the dimensions of the first and second matrices.
System.out.print("Enter the number of rows in the first matrix: ");
int rowsA = scanner.nextInt();
System.out.print("Enter the number of columns in the first matrix: ");
int colsA = scanner.nextInt();
System.out.print("Enter the number of rows in the second matrix: ");
int rowsB = scanner.nextInt();
System.out.print("Enter the number of columns in the second matrix: ");
int colsB = scanner.nextInt();
if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible.");
return;
}
// Create arrays to store the first and second matrices.
int[][] matrixA = new int[rowsA][colsA];
int[][] matrixB = new int[rowsB][colsB];
24
2403031267030 OOPJ Laboratory
return result;
}
}
Output:-
25
Practical-9
26
2403031267030 OOPJ Laboratory
Practical-9
27
2403031267030 OOPJ Laboratory
Output:-
28
Practical-10
29
2403031267030 OOPJ Laboratory
Practical-10
// Default constructor
public Overloading() {
System.out.println("Default constructor");
}
// Parameterized constructor with an integer argument
public Overloading(int x) {
System.out.println("Parameterized constructor with int: " + x);
}
30
2403031267030 OOPJ Laboratory
Output:-
31
Practical-11
32
2403031267030 OOPJ Laboratory
Practical-11
void display() {
System.out.println("This is a shape.");
}
}
// Concrete subclass (Circle)
class Circle extends Shape {
double radius;
34
Practical-12
35
2403031267030 OOPJ Laboratory
Practical-12
36
2403031267030 OOPJ Laboratory
Output:-
37
Practical-13
38
2403031267030 OOPJ Laboratory
Practical-13
Output:-
40
Practical-14
41
2403031267030 OOPJ Laboratory
Practical-14
Output:-
43
Practical-15
44
2403031267030 OOPJ Laboratory
Practical-15
// Method in the outer class to create and use the inner class
void useInnerClass() {
InnerClass inner = new InnerClass(); // Create an instance of the inner class
inner.display(); // Call the display method of the inner class
}
}
Output:-
45
Practical-16
46
2403031267030 OOPJ Laboratory
Practical-16
47
2403031267030 OOPJ Laboratory
Output:-
48
Practical-17
49
2403031267030 OOPJ Laboratory
Practical-17
if (line.isEmpty()) {
break; // Exit the loop when an empty line is entered
}
// Count characters by adding the length of the line
charCount += line.length();
// Split the line into words using space as a delimiter and count words
String[] words = line.split("\\s+");
wordCount += words.length;
Output:-
51
Practical-18
52
2403031267030 OOPJ Laboratory
Practical-18
int left = 0;
int right = str.length() - 1;
return true; // If the loop completes without finding a mismatch, it's a palindrome
}
}
53
2403031267030 OOPJ Laboratory
Output:-
54
Practical-19
55
2403031267030 OOPJ Laboratory
Practical-19
Aim:- Write a Java program that reads a line of integers and then
displays each integer and the sum of all integers. (Use StringTokenizer
class)?
Code:-
import java.util.Scanner;
import java.util.StringTokenizer;
56
2403031267030 OOPJ Laboratory
Output:-
57
Practical-20
58
2403031267030 OOPJ Laboratory
Practical-20
Aim:- Write a java program for creating single try block with multiple
catch blocks.
Code:-
import java.util.InputMismatchException;
import java.util.Scanner;
try {
// Prompt the user to enter a number
System.out.print("Enter a number: ");
int number = scanner.nextInt(); // Read an integer from the user
59
2403031267030 OOPJ Laboratory
Output:-
60
Practical-21
61
2403031267030 OOPJ Laboratory
Practical-21
Aim:- Write a program for multiple try blocks and multiple catch blocks
including finally.
Code:-
public class Main {
public static void main(String[] args) {
// Print a message to the console
System.out.println("Prince_Chhodavadiya");
try {
// Attempt to access an element outside the bounds of the array
int[] numbers = { 1, 2, 3 };
System.out.println(numbers[5]); // This will throw an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
// Handle the specific exception for array index out of bounds
System.out.println("Array index out of bounds!");
}
try {
// Attempt to access the length of a null string
String str = null;
System.out.println(str.length()); // This will throw a NullPointerException
} catch (NullPointerException e) {
// Handle the specific exception for a null pointer
System.out.println("NullPointerException occurred!");
}
try {
// Attempt to perform division by zero
int result = 10 / 0; // This will throw an ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handle the specific exception for arithmetic errors
System.out.println("ArithmeticException occurred!");
} finally {
// This block is executed regardless of whether an exception was thrown
System.out.println("Finally block executed.");
}
62
2403031267030 OOPJ Laboratory
Output:-
63
Practical-22
64
2403031267030 OOPJ Laboratory
Practical-22
try {
// Attempt to set a negative age
int age = -5;
if (age < 0) {
// Throw a CustomException with a custom error message
throw new CustomException("Age cannot be negative");
}
System.out.println("Age: " + age);
} catch (CustomException e) {
// Catch and handle the CustomException
System.out.println("CustomException caught: " + e.getMessage());
}
}
}
Output:-
65
Practical-23
66
2403031267030 OOPJ Laboratory
Practical-23
Aim:- Write a java program for producer and consumer problem using
Threads.
Code:-
import java.util.LinkedList;
import java.util.Queue;
67
2403031267030 OOPJ Laboratory
try {
for (int i = 1; i <= 5; i++) {
buffer.produce(i); // Produce an item and add it to the buffer
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
int item = buffer.consume(); // Consume an item from the buffer
Thread.sleep(1500); // Sleep for 1.5 seconds
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
68
2403031267030 OOPJ Laboratory
Output:-
69
Practical-24
70
2403031267030 OOPJ Laboratory
Practical-24
while (true) {
int number = random.nextInt(100); // Generate a random integer between 0 and 99
System.out.println("Generated: " + number);
// Depending on whether the number is even or odd, create and start threads for square or cube
calculation
if (number % 2 == 0) {
Thread t2 = new Thread(new SquareCalculator(number));
t2.start(); // Start the square calculator thread
} else {
Thread t3 = new Thread(new CubeCalculator(number));
t3.start(); // Start the cube calculator thread
}
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
this.number = number;
}
@Override
public void run() {
int square = number * number;
System.out.println("Square of " + number + ": " + square);
}
}
@Override
public void run() {
int cube = number * number * number;
System.out.println("Cube of " + number + ": " + cube);
}
}
72
Practical-25
73
2403031267030 OOPJ Laboratory
Practical-25
74
Practical-26
75
2403031267030 OOPJ Laboratory
Practical-26
while (true) {
System.out.println("Options:");
System.out.println("1. Add item");
System.out.println("2. Search item");
System.out.println("3. Remove item");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
switch (choice) {
case 1:
System.out.print("Enter item to add: ");
String newItem = scanner.nextLine();
items.add(newItem);
System.out.println("Item added: " + newItem);
break;
case 2:
System.out.print("Enter item to search: ");
String searchItem = scanner.nextLine();
77