r23 Oop Through Java Lab Manual Final
r23 Oop Through Java Lab Manual Final
OBJECT-ORIENTED PROGRAMMING
THROUGH JAVA LAB MANUAL
II B.TECH III SEM
(R23 Regulations)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
Course Name & Code : Object Oriented Programming Through Java lab (23CS54)
L-T-P Structure : 0-0-3 Credits: 1.5
Program/Sem/Sec : B.Tech-CSE / III SEM / A,B, C & D SECTIONS A.Y : 2024-25
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 2 2 - 2 - - - - - - 2 2 - -
CO2 3 2 2 - 2 - - - - - - 2 2 - 2
CO3 3 2 2 - 2 - - - - - - 2 2 - 2
CO4 - - - - - - - 2 2 2 - - - - -
The Computer Science & Engineering aims at providing continuously stimulating educational
environment to its students for attaining their professional goals and meet the global challenges.
• DM1: To develop a strong theoretical and practical background across the computer science
discipline with an emphasis on problem solving.
• DM2: To inculcate professional behaviour with strong ethical values, leadership qualities,
innovative thinking and analytical abilities into the student.
• DM3: Expose the students to cutting edge technologies which enhance their employability and
knowledge.
• DM4: Facilitate the faculty to keep track of latest developments in their research areas and
encourage the faculty to foster the healthy interaction with industry.
• PEO1: Pursue higher education, entrepreneurship and research to compete at global level.
• PEO2: Design and develop products innovatively in computer science and engineering and in
other allied fields.
• PEO3: Function effectively as individuals and as members of a team in the conduct of
interdisciplinary projects; and even at all the levels with ethics and necessary attitude.
• PEO4: Serve ever-changing needs of society with a pragmatic perception.
The ability to apply Software Engineering practices and strategies in software project
PSO 1
development using open-source programming environment for the success of organization.
The ability to design and develop computer programs in networking, web applications and
PSO 2
IoT as per the society needs.
PSO 3 To inculcate an ability to analyse, design and implement database applications.
Modules/ Exercises
Exercise - 1:
a. Write a JAVA program to display default value of all primitive data type of JAVA
b. Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the
discriminate D and basing on value of D, describe the nature of root.
Exercise - 2
a. Write a JAVA program to search for an element in a given list of elements using binary search
mechanism.
b. Write a JAVA program to sort for an element in a given list of elements using bubble sort
c. Write a JAVA program using String Buffer to delete, remove character.
Exercise - 3
a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke them
inside main method.
b. Write a JAVA program implements method overloading.
c. Write a JAVA program to implement constructor.
d. Write a JAVA program to implement constructor overloading.
Exercise - 4
a. Write a JAVA program to implement Single Inheritance.
b. Write a JAVA program to implement multilevel Inheritance.
c. Write a JAVA program for abstract class to find areas of different shape.
Exercise - 5
a. Write a JAVA program give example for “super” keyword.
b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
c. Write a JAVA program that implements Runtime polymorphism.
Exercise - 6
a. Write a JAVA program that describes exception handling mechanism.
b. Write a JAVA program Illustrating Multiple catch clauses.
c. Write a JAVA program for creation of Java Built-in Exceptions.
d. Write a JAVA program for creation of User Defined Exception.
Exercise - 7
a. Write a JAVA program that creates threads by extending Thread class. First thread display “Good
Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display
“Welcome” every 3 seconds (Repeat the same by implementing Runnable).
b. Write a program illustrating is Alive and join ()
c. Write a Program illustrating Daemon Threads.
d. Write a JAVA program Producer Consumer Problem.
Exercise – 8
a. Write a JAVA program that import and use the user defined packages.
b. Without writing any code, build a GUI that display text in label and image in an ImageView (use
JavaFX).
c. Build a Tip Calculator app using several JavaFX components and learn how to respond to user
interactions with the GUI.
Exercise-9:
a. Implement the programs using List Interface and its implemented classes.
b. Implement the programs using Set Interface and its implemented classes.
c. Implement the programs using Map Interface and its implemented classes.
Exercise - 1:
a. Write a JAVA program to display default value of all primitive data type of JAVA
class DefaultValues {
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bool;
void displayDefaults() {
System.out.println("Default Values of Primitive Data Types:");
System.out.println("Byte: " + b);
System.out.println("Short: " + s);
System.out.println("Int: " + i);
System.out.println("Long: " + l);
System.out.println("Float: " + f);
System.out.println("Double: " + d);
System.out.println("Char: [" + c + "] (empty character)");
System.out.println("Boolean: " + bool);
}
Expected Output:
b. Write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate the
discriminate D and basing on value of D, describe the nature of root.
import java.util.Scanner;
class QuadraticEquation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input coefficients
System.out.print("Enter coefficient a: ");
double a = sc.nextDouble();
// Calculate discriminant
double D = b * b - 4 * a * c;
System.out.println("Discriminant (D) = " + D);
sc.close();
}
}
Example Output:
Enter coefficient a: 1
Enter coefficient b: -7
Enter coefficient c: 10
Discriminant (D) = 9.0
Roots are real and distinct.
Root 1: 5.0
Root 2: 2.0
Exercise - 2
a. Write a JAVA program to search for an element in a given list of elements using binary search
mechanism.
import java.util.Scanner;
class BinarySearch {
// Method to perform binary search
public static int binarySearch(int[] arr, int key) {
int left = 0, right = arr.length - 1;
// Display result
if (result != -1) {
sc.close();
}
}
Expected Output:
b. Write a JAVA program to sort for an element in a given list of elements using bubble sort.
import java.util.Scanner;
class BubbleSort {
// Method to perform Bubble Sort
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
bubbleSort(arr);
Expected Output:
Exercise - 3
a. Write a JAVA program to implement class mechanism. Create a class, methods and invoke
them inside main method.
// Define a class
class Student {
// Data members (instance variables)
String name;
int age;
Expected Output:
Student Information:
Student Name: Alice
Student Age: 20
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
Expected Output:
class Student {
String name;
int age;
Expected Output:
System.out.println("Student 1:");
s1.display();
System.out.println("\nStudent 2:");
s2.display();
System.out.println("\nStudent 3:");
s3.display();
}
}
Expected Output:
Student 1:
Student Name: Unknown
Student Age: 0
Student 2:
Student Name: Alice
Student Age: 18
Student 3:
Student Name: Bob
Student Age: 21
Exercise - 4
a. Write a JAVA program to implement Single Inheritance.
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
Expected Output:
Expected Output:
c. Write a JAVA program for abstract class to find areas of different shape.
// Abstract class
abstract class Shape {
// Abstract method to calculate area
abstract void calculateArea();
}
// Constructor
Circle(double r) {
radius = r;
}
// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
// Constructor
Triangle(double b, double h) {
base = b;
height = h;
}
// Calculating areas
circle.calculateArea();
rectangle.calculateArea();
triangle.calculateArea();
}
}
Expected Output:
Exercise - 5
a. Write a JAVA program give example for “super” keyword.
// Parent class
class Animal {
String name = "Animal";
Expected Output:
b. Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
// Interface definition
interface Shape {
// Abstract method (no implementation)
void calculateArea();
}
// Constructor
Circle(double r) {
radius = r;
}
// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
// Calculating areas
circle.calculateArea();
rectangle.calculateArea();
}
}
Expected Output:
// First interface
interface Animal {
void eat();
}
// Second interface
interface Bird {
void fly();
}
Expected Output:
// Child class 1
class Dog extends Animal {
// Overriding makeSound() method
void makeSound() {
System.out.println("Dog barks.");
}
}
// Child class 2
class Cat extends Animal {
// Overriding makeSound() method
void makeSound() {
System.out.println("Cat meows.");
}
}
public class RuntimePolymorphismExample {
public static void main(String[] args) {
// Parent class reference pointing to Child class objects (Upcasting)
Animal myAnimal;
myAnimal = new Dog();
myAnimal.makeSound(); // Calls Dog's version of makeSound()
myAnimal = new Cat();
myAnimal.makeSound(); // Calls Cat's version of makeSound()
}
}
Expected Output:
Dog barks.
Cat meows.
Exercise - 6
a. Write a JAVA program that describes exception handling mechanism.
Expected Output:
} catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero is not allowed.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: Array index is out of bounds.");
} catch (Exception e) {
System.out.println("Exception caught: General exception occurred.");
} finally {
System.out.println("Execution completed.");
}
}
}
Expected Output:
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
}
try {
// 2. ArrayIndexOutOfBoundsException (Invalid index access)
int arr[] = {1, 2, 3};
System.out.println("Array Element: " + arr[5]); // Causes ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
try {
// 3. NullPointerException (Accessing method on null object)
String str = null;
System.out.println("String length: " + str.length()); // Causes NullPointerException
} catch (NullPointerException e) {
System.out.println("Exception caught: " + e);
}
Expected Output:
Expected Output:
Exercise - 7
a. Write a JAVA program that creates threads by extending Thread class. First thread display
“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third
display “Welcome” every 3 seconds (Repeat the same by implementing Runnable).
Expected Output:
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
...
// Starting threads
t1.start();
t2.start();
t3.start();
}
}
Expected Output:
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
...
Expected Output:
try {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
Thread.sleep(1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
System.out.println("Thread Interrupted: " + e);
}
}
}
public class DaemonThreadDemo {
public static void main(String[] args) {
// Creating daemon and user threads
DaemonThreadExample t1 = new DaemonThreadExample(); // User thread
DaemonThreadExample t2 = new DaemonThreadExample(); // Daemon thread
Expected Output:
// Producer method
public synchronized void produce(int item) throws InterruptedException {
while (buffer.size() == capacity) {
System.out.println("Buffer is full. Producer waiting...");
wait(); // Wait if buffer is full
}
buffer.add(item);
System.out.println("Produced: " + item);
notify(); // Notify consumer
}
// Consumer method
public synchronized int consume() throws InterruptedException {
while (buffer.isEmpty()) {
System.out.println("Buffer is empty. Consumer waiting...");
wait(); // Wait if buffer is empty
}
// Producer thread
class Producer extends Thread {
private SharedBuffer buffer;
Producer(SharedBuffer buffer) {
this.buffer = buffer;
// Consumer thread
class Consumer extends Thread {
private SharedBuffer buffer;
Consumer(SharedBuffer buffer) {
this.buffer = buffer;
}
// Main class
public class ProducerConsumerDemo {
public static void main(String[] args) {
// Starting threads
producer.start();
consumer.start();
}
}
Expected Output:
Produced: 1
Consumed: 1
Produced: 2
Produced: 3
Consumed: 2
Produced: 4
Produced: 5
Consumed: 3
Produced: 6
Buffer is full. Producer waiting...
Consumed: 4
Produced: 7
...
Exercise – 8
a. Write a JAVA program that import and use the user defined packages.
Expected Output:
javac MainProgram.java
java MainProgram
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
b. Without writing any code, build a GUI that display text in label and image in an ImageView
(use JavaFX).
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
// Load an image (Ensure the image file exists in the project directory)
Image image = new Image("file:example.jpg"); // Change the path accordingly
ImageView imageView = new ImageView(image);
Expected Output:
c. Build a Tip Calculator app using several JavaFX components and learn how to respond to
user interactions with the GUI.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
// Label and TextField for Bill Amount
Label billLabel = new Label("Enter Bill Amount:");
TextField billInput = new TextField();
billInput.setPromptText("Enter amount");
// Update Labels
tipAmountLabel.setText(String.format("Tip Amount: $%.2f", tipAmount));
totalAmountLabel.setText(String.format("Total Amount: $%.2f", totalAmount));
} catch (NumberFormatException ex) {
tipAmountLabel.setText("Invalid input! Enter a valid number.");
totalAmountLabel.setText("");
}
});
Exercise-9:
a. Implement the programs using List Interface and its implemented classes.
import java.util.ArrayList;
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Accessing elements
System.out.println("Fruits List: " + fruits);
// Removing an element
fruits.remove("Banana");
System.out.println("After Removing Banana: " + fruits);
Expected Output:
import java.util.LinkedList;
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.addFirst(5); // Adding at the beginning
numbers.addLast(30); // Adding at the end
// Displaying elements
System.out.println("LinkedList: " + numbers);
// Removing elements
numbers.removeFirst();
numbers.removeLast();
Expected Output:
import java.util.Vector;
// Adding elements
cities.add("New York");
cities.add("London");
cities.add("Tokyo");
// Display elements
System.out.println("Cities: " + cities);
// Removing an element
cities.remove("London");
Expected Output:
import java.util.Stack;
// Displaying stack
System.out.println("Stack: " + books);
// Popping an element
System.out.println("Popped: " + books.pop());
Expected Output:
b. Implement the programs using Set Interface and its implemented classes.
import java.util.HashSet;
// Adding elements
colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Yellow");
colors.add("Blue"); // Duplicate element (ignored)
// Displaying elements
System.out.println("HashSet: " + colors);
// Removing an element
colors.remove("Green");
Expected Output:
import java.util.LinkedHashSet;
// Adding elements
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(10); // Duplicate (ignored)
// Removing an element
numbers.remove(20);
Expected Output:
import java.util.TreeSet;
// Adding elements
sortedNumbers.add(50);
sortedNumbers.add(10);
sortedNumbers.add(30);
sortedNumbers.add(40);
sortedNumbers.add(20);
// Removing an element
sortedNumbers.remove(30);
Expected Output:
c. Implement the programs using Map Interface and its implemented classes.
import java.util.HashMap;
import java.util.Map;
// Removing an entry
students.remove(103);
Expected Output:
import java.util.LinkedHashMap;
import java.util.Map;
// Removing an entry
countries.remove(3);
import java.util.TreeMap;
import java.util.Map;
// Removing an entry
employees.remove(2002);
Expected Output: