0% found this document useful (0 votes)
3 views77 pages

OOP Java Lab (23ACS08) Materials - R23

The document outlines the course structure and syllabus for the B.Tech in Computer Science and Engineering under R23 regulations, focusing on Object Oriented Programming through Java. It includes course objectives, a list of experiments covering fundamental Java concepts, sample exercises, and references for textbooks and online resources. The syllabus emphasizes practical programming skills, including classes, inheritance, exception handling, threads, and JDBC connectivity.

Uploaded by

waseemshaikaa
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)
3 views77 pages

OOP Java Lab (23ACS08) Materials - R23

The document outlines the course structure and syllabus for the B.Tech in Computer Science and Engineering under R23 regulations, focusing on Object Oriented Programming through Java. It includes course objectives, a list of experiments covering fundamental Java concepts, sample exercises, and references for textbooks and online resources. The syllabus emphasizes practical programming skills, including classes, inheritance, exception handling, threads, and JDBC connectivity.

Uploaded by

waseemshaikaa
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

[Link].

– COMPUTER SCIENCE AND ENGINEERING COURSE STRUCTURE & II YEAR


SYLLABUS
- R23 REGULATIONS
II Year I Object Oriented Programming through Java Lab - L T P C
Semester 23ACS08
0 0 3 1.5

Course Objectives: The aim of this course is to


 Practice object-oriented programming in the Java programming language
 Implement Classes, Objects, Methods, Inheritance, Exception, Runtime Polymorphism,
User defined Exception handling mechanism
 Illustrate inheritance, Exception handling mechanism, JDBC connectivity
 Construct Threads, Event Handling, implement packages, Java FX GUI

Experiments covering the Topics:


 Object Oriented Programming fundamentals- data types, control structures
 Classes, methods, objects, Inheritance, polymorphism,
 Exception handling, Threads, Packages, Interfaces
 Files, I/O streams, JavaFX GUI

Sample Experiments:
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 StringBuffer 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 to implement 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 multi-level Inheritance c) Write a JAVA program for abstract class to
find areas of different shapes
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 isAlive 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) Write a java program that connects to a database using JDBC
b) Write a java program to connect to a database using JDBC and insert values into it.
c) Write a java program to connect to a database using JDBC and delete values from it

Textbooks:
1. JAVA one step ahead, Anitha Seth, B.L. Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object-Oriented Programming, Debasis Samanta,
Monalisa Sarma, Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson.

References Books:
1. The complete Reference Java, 11th edition, Herbert Schildt,TMH
2. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson

Online Resources:
1. [Link]
2.
[Link]
_shared/overview
Exercise – 1:
a) Write a JAVA program to display default value of all primitive data type of JAVA

Java program that displays the default values of all primitive data types in Java:

Sample1:

public class Demo {


static boolean val1;
static double val2;
static float val3;
static int val4;
static long val5;
static String val6;
public static void main(String[] args) {
[Link]("Default values ....");
[Link]("Val1 = " + val1);
[Link]("Val2 = " + val2);
[Link]("Val3 = " + val3);
[Link]("Val4 = " + val4);
[Link]("Val5 = " + val5);
[Link]("Val6 = " + val6);
}
}

Output:

Default values.....
Val1 = false
Val2 = 0.0
Val3 = 0.0
Val4 = 0
Val5 = 0
Val6 = null

Sample2:

public class DefaultValues {


// Define instance variables for each primitive data type
byte defaultByte;
short defaultShort;
int defaultInt;
long defaultLong;
float defaultFloat;
double defaultDouble;
char defaultChar;
boolean defaultBoolean;

public static void main(String[] args) {


// Create an instance of the DefaultValues class
DefaultValues values = new DefaultValues();

// Display the default values of each primitive data type


[Link]("Default value of byte: " + [Link]);
[Link]("Default value of short: " +
[Link]);
[Link]("Default value of int: " + [Link]);
[Link]("Default value of long: " + [Link]);
[Link]("Default value of float: " +
[Link]);
[Link]("Default value of double: " +
[Link]);
[Link]("Default value of char: " + [Link]);
[Link]("Default value of boolean: " +
[Link]);
}
}

When you run this program, it will display these default values.

Output:

Default value of byte: 0


Default value of short: 0

Default value of int: 0

Default value of long: 0

Default value of float: 0.0

Default value of double: 0.0

Default value of char:

b) Write a java program that display the roots of a quadratic equation ax2+bx+c=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

Java program that calculates the roots of a quadratic equation ax2+bx=0, computes the
discriminant DDD, and describes the nature of the roots based on the value of DDD:

import [Link];

public class QuadraticEquation {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Get the coefficients a, b, and c from the user


[Link]("Enter coefficient a: ");
double a = [Link]();
[Link]("Enter coefficient b: ");
double b = [Link]();
[Link]("Enter coefficient c: ");
double c = [Link]();

// Calculate the discriminant D


double D = b * b - 4 * a * c;

// Determine the nature of the roots


if (D > 0) {
[Link]("The equation has two real and distinct
roots.");
double root1 = (-b + [Link](D)) / (2 * a);
double root2 = (-b - [Link](D)) / (2 * a);
[Link]("Root 1: " + root1);
[Link]("Root 2: " + root2);
} else if (D == 0) {
[Link]("The equation has one real and repeated
root.");
double root = -b / (2 * a);
[Link]("Root: " + root);
} else {
[Link]("The equation has two complex roots.");
double realPart = -b / (2 * a);
double imaginaryPart = [Link](-D) / (2 * a);
[Link]("Root 1: " + realPart + " + " + imaginaryPart
+ "i");
[Link]("Root 2: " + realPart + " - " + imaginaryPart
+ "i");
}

[Link]();
}
}

Running the Program

When you run this program, it will prompt you to enter the coefficients aaa, bbb, and ccc of
the quadratic equation. Based on these inputs, it will calculate and display the roots of the
equation and describe their nature.

Output:
Enter coefficient a: 2
Enter coefficient b: 3
Enter coefficient c: 1
The equation has two real and distinct roots.
Root 1: -0.5
Root 2: -1.0
Exercise - 2
a) Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.

Java program that implements binary search to find an element in a sorted list:

Sample1:

import [Link];

// Binary Search in Java

class BinarySearch {

int binarySearch(int array[], int element, int low, int high) {

// Repeat until the pointers low and high meet each other

while (low <= high) {

// get index of mid element

int mid = low + (high - low) / 2;

// if element to be searched is the mid element

if (array[mid] == element)

return mid;

// if element is less than mid element

// search only the left side of mid

if (array[mid] < element)

low = mid + 1;

// if element is greater than mid element

// search only the right side of mid

else

high = mid - 1;

return -1;
}

public static void main(String args[]) {

// create an object of Main class

BinarySearch obj = new BinarySearch();

// create a sorted array

int[] array = { 3, 4, 5, 6, 7, 8, 9 };

int n = [Link];

// get input from user for element to be searched

Scanner input = new Scanner([Link]);

[Link]("Enter element to be searched:");

// element to be searched

int element = [Link]();

[Link]();

// call the binary search method

// pass arguments: array, element, index of first and last element

int result = [Link](array, element, 0, n - 1);

if (result == -1)

[Link]("Not found");

else

[Link]("Element found at index " + result);

Output:

Enter element to be searched:


3
Element found at index 0
Sample2:

import [Link];
import [Link];

public class BinarySearchExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Get the number of elements from the user


[Link]("Enter the number of elements: ");
int n = [Link]();

// Create an array to hold the elements


int[] array = new int[n];

// Get the elements from the user


[Link]("Enter the elements in sorted order:");
for (int i = 0; i < n; i++) {
array[i] = [Link]();
}

// Get the element to search for


[Link]("Enter the element to search for: ");
int key = [Link]();

// Perform binary search


int result = binarySearch(array, key);

// Print the result


if (result == -1) {
[Link]("Element not found in the list.");
} else {
[Link]("Element found at index: " + result);
}

[Link]();
}

// Binary search method


public static int binarySearch(int[] array, int key) {
int left = 0;
int right = [Link] - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if key is present at mid


if (array[mid] == key) {
return mid;
}

// If key is greater, ignore left half


if (array[mid] < key) {
left = mid + 1;
} else {
// If key is smaller, ignore right half
right = mid - 1;
}
}

// If we reach here, the element was not present


return -1;
}
}

Output:
Enter the number of elements: 3
Enter the elements in sorted order:
135
Enter the element to search for: 5
Element found at index: 2

b) Write a JAVA program to sort for an element in a given list of elements using bubble
sort.
Sample1:
// Java program for implementation
// of Bubble Sort
class BubbleSort {
void bubbleSort(int arr[])
{
int n = [Link];
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

// Prints the array


void printArray(int arr[])
{
int n = [Link];
for (int i = 0; i < n; ++i)
[Link](arr[i] + " ");
[Link]();
}

// Driver method to test above


public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
[Link](arr);
[Link]("Sorted array");
[Link](arr);
}
}

Output:
Enter element to be searched:
5
Element found at index 2
Sample2:

Java program that uses the Bubble Sort algorithm to sort a list of elements and then search for
a specific element within the sorted list:

import [Link];

public class BubbleSortSearch {

// Function to perform Bubble Sort


public static void bubbleSort(int[] arr) {
int n = [Link];
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - 1 - i; 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;
swapped = true;
}
}
// If no two elements were swapped by inner loop, then the list
is sorted
if (!swapped) break;
}
}

// Function to search for an element in the sorted array


public static int search(int[] arr, int key) {
int n = [Link];
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index of the found element
}
}
return -1; // Return -1 if the element is not found
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Input: Number of elements in the array


[Link]("Enter the number of elements: ");
int n = [Link]();

int[] arr = new int[n];

// Input: Elements of the array


[Link]("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Sorting the array using Bubble Sort


bubbleSort(arr);

// Output: Sorted array


[Link]("Sorted array:");
for (int i : arr) {
[Link](i + " ");
}
[Link]();

// Input: Element to search for


[Link]("Enter the element to search: ");
int key = [Link]();

// Searching for the element in the sorted array


int index = search(arr, key);

// Output: Search result


if (index != -1) {
[Link]("Element found at index: " + index);
} else {
[Link]("Element not found in the array.");
}

[Link]();
}
}

How it works:

1. Bubble Sort: The bubbleSort method sorts the array in ascending order by repeatedly
swapping adjacent elements if they are in the wrong order.
2. Search: The search method searches for a specific element in the sorted array. If
found, it returns the index of the element; otherwise, it returns -1.
3. Main Method:
o It prompts the user to input the number of elements and the elements
themselves.
o It then sorts the array and displays it.
o Finally, it prompts the user for an element to search and displays the result of
the search.
You can run this program in any Java development environment or online Java compiler.

Output:
Enter the number of elements: 3
Enter the elements:
153
Sorted array:
135
Enter the element to search: 5
Element found at index: 2

c) Write a JAVA program using StringBuffer to delete, remove character.


Sample1:
// Java program to illustrate the
// [Link]()
import [Link].*;
public class StringBufferEx {
public static void main(String[] args)
{
StringBuffer sbf = new StringBuffer("Nandakumar");
[Link]("string buffer = " + sbf);
// Deleting characters from index 2 to 7
[Link](6, 8);
[Link]("After deletion string buffer is = " + sbf);
}
}
Output:
string buffer = Nandakumar
After deletion string buffer is = Nandakar
Sample2:

Java program that demonstrates how to use the StringBuffer class to delete and remove
characters from a string:

import [Link];

public class StringBufferExample {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Input: Original string


[Link]("Enter a string: ");
String inputString = [Link]();

// Create a StringBuffer object from the input string


StringBuffer stringBuffer = new StringBuffer(inputString);

// Display the original string


[Link]("Original string: " + stringBuffer);

// Input: Character to remove


[Link]("Enter the character to remove: ");
char charToRemove = [Link]().charAt(0);

// Remove the first occurrence of the specified character


for (int i = 0; i < [Link](); i++) {
if ([Link](i) == charToRemove) {
[Link](i);
break; // Remove only the first occurrence
}
}

// Display the string after removing the character


[Link]("String after removing character: " +
stringBuffer);

// Input: Start and end positions to delete a substring


[Link]("Enter the start index for deletion: ");
int startIndex = [Link]();

[Link]("Enter the end index for deletion: ");


int endIndex = [Link]();

// Delete the substring from the specified range


if (startIndex >= 0 && endIndex <= [Link]() &&
startIndex < endIndex) {
[Link](startIndex, endIndex);
} else {
[Link]("Invalid indices for deletion.");
}

// Display the string after deleting the substring


[Link]("String after deletion: " + stringBuffer);

[Link]();
}
}

Explanation:

1. StringBuffer Object:
o We use StringBuffer to create a modifiable string. Unlike String,
StringBuffer allows for in-place modifications like deletion, appending, and
replacement.
2. Removing a Character:
o The program removes the first occurrence of a specified character using the
deleteCharAt(int index) method of StringBuffer. It traverses the string
to find the character and removes it.
3. Deleting a Substring:
o The user specifies a start and end index, and the program deletes the substring
in that range using the delete(int start, int end) method. The deletion
range includes the character at start but excludes the character at end.
4. User Input:
o The program takes user input to determine the string, the character to remove,
and the indices for deletion.

Example Usage:

 If the user inputs "Hello World" as the string, 'o' as the character to remove, 4 as the
start index, and 7 as the end index:
o After removing the first 'o': "Hell World"
o After deleting from index 4 to 7: "Hellld"

This program showcases how flexible StringBuffer is for string manipulation tasks.

Output:

Enter a string: Nanda

Original string: Nanda

Enter the character to remove: a

String after removing character: Nnda

Enter the start index for deletion: 1

Enter the end index for deletion: 2

String after deletion: Nda


Exercise - 3
a) Write a JAVA program to implement class mechanism. Create a class, methods and
invoke them inside main method.

The simple Java program that demonstrates the use of classes, methods, and how to invoke
them inside the main method.

Java Program: Class Mechanism

Sample1:

// Java Program for class example

class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
[Link]([Link]);
[Link]([Link]);
}
}

Output:
0
null

Sample2:
// Define a class named "Car"
class Car {
// Attributes (fields) of the Car class
String make;
String model;
int year;
// Constructor to initialize the Car object
Car(String make, String model, int year) {
[Link] = make;
[Link] = model;
[Link] = year;
}
// Method to display car details
void displayDetails() {
[Link]("Car Make: " + make);
[Link]("Car Model: " + model);
[Link]("Car Year: " + year);
}
// Method to start the car
void start() {
[Link](make + " " + model + " is starting.");
}
// Method to stop the car
void stop() {
[Link](make + " " + model + " is stopping.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Corolla", 2022);

// Invoke methods on the Car object


[Link]();
[Link]();
[Link]();
}
}

Explanation:

1. Class Definition (Car):


o The Car class has three attributes: make, model, and year.
o It has a constructor that initializes these attributes when a Car object is created.
o The class includes three methods: displayDetails(), start(), and stop(),
which perform different actions.
2. Main Class (Main):
o Inside the main method, a Car object (myCar) is created with the specified make,
model, and year.
o The methods displayDetails(), start(), and stop() are invoked on the
myCar object.

Output:When you run this program, you will get the following output:
Car Make: Toyota
Car Model: Corolla
Car Year: 2022
Toyota Corolla is starting.
Toyota Corolla is stopping.

This example demonstrates how to define a class with methods and how to create and interact
with objects of that class in Java.
b) Write a JAVA program implement method overloading.
Sample1:

// Java program to demonstrate working of method


// overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}

Output
30
60
31.0

Sample2:

Java program that demonstrates method overloading, which allows a class to have more than
one method with the same name, but different parameters.
Java Program: Method Overloading
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


double add(double a, double b) {
return a + b;
}

// Overloaded method to concatenate two strings


String add(String a, String b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
// Create an object of MathOperations class
MathOperations mathOps = new MathOperations();

// Call the add method with two integers


int sum1 = [Link](10, 20);
[Link]("Sum of 10 and 20: " + sum1);

// Call the add method with three integers


int sum2 = [Link](10, 20, 30);
[Link]("Sum of 10, 20, and 30: " + sum2);

// Call the add method with two double values


double sum3 = [Link](10.5, 20.5);
[Link]("Sum of 10.5 and 20.5: " + sum3);

// Call the add method with two strings


String result = [Link]("Hello, ", "World!");
[Link]("Concatenation of 'Hello, ' and 'World!': " +
result);
}
}

Explanation:

1. Method Overloading:
o The MathOperations class contains four overloaded add methods.
o Each method has the same name (add), but different parameters:
 add(int a, int b): Adds two integers.
 add(int a, int b, int c): Adds three integers.
 add(double a, double b): Adds two double values.
 add(String a, String b): Concatenates two strings.
2. Main Class (Main):
o Inside the main method, an object of MathOperations is created.
o Different overloaded add methods are called based on the arguments passed.

Output:

When you run this program, you will get the following output:

Sum of 10 and 20: 30


Sum of 10, 20, and 30: 60
Sum of 10.5 and 20.5: 31.0
Concatenation of 'Hello, ' and 'World!': Hello, World!

This example demonstrates how method overloading works in Java, allowing you to use the
same method name with different types or numbers of parameters to perform different tasks.

c) Write a JAVA program to implement constructor.


Sample1:

Java program that demonstrates the use of constructors. Constructors are special methods used
to initialize objects when they are created. They have the same name as the class and no return
type.

Java Program: Implementing a Constructor


class Person {
// Attributes (fields) of the Person class
String name;
int age;

// Constructor to initialize the Person object


Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Method to display person details


void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Person class using the constructor
Person person1 = new Person("Alice", 30);

// Call the method to display person details


[Link]();
}
}
Explanation:

1. Class Definition (Person):


o The Person class has two attributes: name and age.
o It has a constructor Person(String name, int age) that initializes these
attributes when a Person object is created.
o The displayDetails() method is used to print the details of the Person.
2. Main Class (Main):
o Inside the main method, a Person object (person1) is created using the
constructor, with "Alice" as the name and 30 as the age.
o The displayDetails() method is invoked on the person1 object to print the
person's details.

Output:

When you run this program, you will get the following output:

Name: Alice
Age: 30

This program demonstrates how to define and use a constructor to initialize objects in Java.
The constructor is automatically called when a new object is created, setting the initial values
for the object's fields.

Sample2:
Java Constructor
class Main {
private String name;
// constructor
Main() {
[Link]("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
[Link]("The name is " + [Link]);
}
}
Output:
Constructor Called:
The name is Programiz

d) Write a JAVA program to implement constructor overloading.


Sample1:

// Java program to illustrate


// Constructor Overloading
class Box {
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box() { width = height = depth = 0; }

// constructor used when cube is created


Box(double len) { width = height = depth = len; }

// compute and return volume


double volume() { return width * height * depth; }
}

// Driver code
public class Test {
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;
// get volume of first box
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);

// get volume of second box


vol = [Link]();
[Link]("Volume of mybox2 is " + vol);

// get volume of cube


vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}

Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

Sample2:

Constructor overloading in Java allows a class to have more than one constructor, each with a
different parameter list. This is useful for initializing objects in different ways.

Java Program: Constructor Overloading


class Rectangle {
// Attributes (fields) of the Rectangle class
int length;
int width;

// Constructor with no parameters (default constructor)


Rectangle() {
length = 0;
width = 0;
}

// Constructor with one parameter (square)


Rectangle(int side) {
length = side;
width = side;
}

// Constructor with two parameters (rectangle)


Rectangle(int length, int width) {
[Link] = length;
[Link] = width;
}

// Method to calculate the area of the rectangle


int area() {
return length * width;
}

// Method to display the rectangle's dimensions and area


void displayDetails() {
[Link]("Length: " + length);
[Link]("Width: " + width);
[Link]("Area: " + area());
}
}

public class Main {


public static void main(String[] args) {
// Create a Rectangle object using the default constructor
Rectangle rect1 = new Rectangle();
[Link]("Rectangle 1:");
[Link]();

// Create a Rectangle object using the constructor with one parameter


Rectangle rect2 = new Rectangle(5);
[Link]("\nRectangle 2:");
[Link]();

// Create a Rectangle object using the constructor with two


parameters
Rectangle rect3 = new Rectangle(4, 7);
[Link]("\nRectangle 3:");
[Link]();
}
}

Explanation:

1. Class Definition (Rectangle):


o The Rectangle class has two attributes: length and width.
o Constructor Overloading:
 Default Constructor (Rectangle()): Initializes length and width to
0.
 Constructor with One Parameter (Rectangle(int side)):
Initializes a square by setting both length and width to the same value.
 Constructor with Two Parameters (Rectangle(int length, int
width)): Initializes the rectangle with specified length and width.
o The area() method calculates the area of the rectangle.
o The displayDetails() method prints the dimensions and area of the rectangle.
2. Main Class (Main):
o Inside the main method, three Rectangle objects are created using different
constructors:
 rect1 uses the default constructor.
 rect2 uses the constructor with one parameter, creating a square.
 rect3 uses the constructor with two parameters, creating a rectangle.
o The displayDetails() method is called on each object to display its
properties.
Output:

When you run this program, you will get the following output:

Rectangle 1:
Length: 0
Width: 0
Area: 0

Rectangle 2:
Length: 5
Width: 5
Area: 25

Rectangle 3:
Length: 4
Width: 7
Area: 28

This program demonstrates constructor overloading in Java, where the Rectangle class has
multiple constructors to initialize objects in different ways.
Exercise - 4
a) Write a JAVA program to implement Single Inheritance
Sample1:

Single inheritance in Java is when a class (subclass) inherits from a single parent class
(superclass). Here's an example that demonstrates single inheritance:

Java Program: Single Inheritance


// Superclass (Parent Class)
class Animal {
// Method in the superclass
void eat() {
[Link]("This animal eats food.");
}
}

// Subclass (Child Class) inheriting from Animal


class Dog extends Animal {
// Method in the subclass
void bark() {
[Link]("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Dog class
Dog myDog = new Dog();

// Call the method of the superclass


[Link]();

// Call the method of the subclass


[Link]();
}
}

Explanation:

1. Superclass (Animal):
o The Animal class has a method eat() which prints a message.
2. Subclass (Dog):
o The Dog class inherits from the Animal class using the extends keyword.
o It has its own method bark() which prints a message.
3. Main Class (Main):
o Inside the main method, an object of the Dog class (myDog) is created.
o The eat() method (inherited from the Animal class) is called using the myDog
object.
o The bark() method (defined in the Dog class) is also called using the myDog
object.
Output:

When you run this program, you will get the following output:

This animal eats food.


The dog barks.

This example demonstrates single inheritance in Java, where the Dog class inherits the
properties and behaviors of the Animal class. The Dog class can use both its own methods and
the inherited methods from the Animal class.

Sample2:
// Java program to illustrate the
// concept of single inheritance
import [Link].*;
import [Link].*;
import [Link].*;

// Parent class
class One {
public void print_geek()
{
[Link]("Geeks");
}
}

class Two extends One {


public void print_for() { [Link]("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks
b) Write a JAVA program to implement multi-level Inheritance
Sample1:

In multilevel inheritance, a class is derived from another class, which is also derived from
another class. This creates a chain of inheritance. Below is an example of a Java program that
demonstrates multilevel inheritance.

Java Program: Multilevel Inheritance


// Superclass (Base Class)
class Animal {
// Method in the superclass
void eat() {
[Link]("This animal eats food.");
}
}

// Subclass (Intermediate Class) inheriting from Animal


class Dog extends Animal {
// Method in the Dog class
void bark() {
[Link]("The dog barks.");
}
}

// Subclass (Derived Class) inheriting from Dog


class Puppy extends Dog {
// Method in the Puppy class
void weep() {
[Link]("The puppy weeps.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Puppy class
Puppy myPuppy = new Puppy();

// Call methods from the Puppy class


[Link](); // Inherited from Animal class
[Link](); // Inherited from Dog class
[Link](); // Defined in Puppy class
}
}

Explanation:

1. Superclass (Animal):
o The Animal class has a method eat() that prints a message.
2. Intermediate Class (Dog):
o The Dog class inherits from the Animal class using the extends keyword.
o It has its own method bark() that prints a message.
3. Derived Class (Puppy):
o The Puppy class inherits from the Dog class using the extends keyword.
o It has its own method weep() that prints a message.
4. Main Class (Main):
o Inside the main method, an object of the Puppy class (myPuppy) is created.
o The myPuppy object can call the eat() method (inherited from the Animal
class), the bark() method (inherited from the Dog class), and the weep()
method (defined in the Puppy class).

Output:

When you run this program, you will get the following output:

This animal eats food.


The dog barks.
The puppy weeps.

This example demonstrates multilevel inheritance in Java, where the Puppy class inherits from
the Dog class, which in turn inherits from the Animal class. This allows the Puppy class to
access methods from both the Dog and Animal classes, in addition to its own methods.

Sample2:
// Importing required libraries
import [Link].*;
import [Link].*;
import [Link].*;

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
[Link]("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One {
// Method to print "for"
public void print_for() {
[Link]("for");
}
}

// Child class Three inherits from class Two


class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
[Link]("Geeks");
}
}

// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print_lastgeek();
}
}

Output
Geeks
for
Geeks

c) Write a JAVA program for abstract class to find areas of different shapes
Sample1:

Here's an example of a Java program that uses an abstract class to define a method for
calculating the area of different shapes. The abstract class provides a blueprint, and the
subclasses implement the actual area calculation for each specific shape.

Java Program: Abstract Class to Find Areas of Different Shapes


// Abstract class Shape
abstract class Shape {
// Abstract method to calculate the area
abstract double calculateArea();
}

// Subclass for Rectangle


class Rectangle extends Shape {
double length, width;

// Constructor for Rectangle


Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}

// Implementation of calculateArea method for Rectangle


@Override
double calculateArea() {
return length * width;
}
}
// Subclass for Circle
class Circle extends Shape {
double radius;

// Constructor for Circle


Circle(double radius) {
[Link] = radius;
}

// Implementation of calculateArea method for Circle


@Override
double calculateArea() {
return [Link] * radius * radius;
}
}

// Subclass for Triangle


class Triangle extends Shape {
double base, height;

// Constructor for Triangle


Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}

// Implementation of calculateArea method for Triangle


@Override
double calculateArea() {
return 0.5 * base * height;
}
}

public class Main {


public static void main(String[] args) {
// Create objects for each shape and calculate their areas

// Rectangle with length 5 and width 7


Shape rectangle = new Rectangle(5, 7);
[Link]("Area of Rectangle: " +
[Link]());

// Circle with radius 3.5


Shape circle = new Circle(3.5);
[Link]("Area of Circle: " + [Link]());

// Triangle with base 4 and height 6


Shape triangle = new Triangle(4, 6);
[Link]("Area of Triangle: " + [Link]());
}
}

Explanation:

1. Abstract Class (Shape):


o The Shape class is declared as abstract, meaning it cannot be instantiated
directly.
o It contains an abstract method calculateArea() that must be implemented by
any subclass.
2. Subclass for Rectangle (Rectangle):
o The Rectangle class extends the Shape class.
o It has a constructor to initialize the length and width of the rectangle.
o The calculateArea() method is overridden to provide the area calculation
specific to a rectangle.
3. Subclass for Circle (Circle):
o The Circle class extends the Shape class.
o It has a constructor to initialize the radius of the circle.
o The calculateArea() method is overridden to provide the area calculation
specific to a circle using the formula π * r^2.
4. Subclass for Triangle (Triangle):
o The Triangle class extends the Shape class.
o It has a constructor to initialize the base and height of the triangle.
o The calculateArea() method is overridden to provide the area calculation
specific to a triangle using the formula 0.5 * base * height.
5. Main Class (Main):
o Inside the main method, objects of Rectangle, Circle, and Triangle are
created using their respective constructors.
o The calculateArea() method is called for each shape object to print the area.

Output:

When you run this program, you will get the following output:

Area of Rectangle: 35.0


Area of Circle: 38.48451000647496
Area of Triangle: 12.0

This example demonstrates how to use an abstract class in Java to define a common interface
for different shapes, and then implement the specific area calculations in the subclasses.

Sample2:
// [Link]

// Define an abstract class named Shape

abstract class Shape {

// Declare an abstract method to calculate the area

abstract double calculateArea();

// Declare an abstract method to calculate the perimeter

abstract double calculatePerimeter();

}
// [Link]

// Define a subclass named Circle that extends Shape

class Circle extends Shape {

// Declare a private double variable to store the radius

private double radius;

// Constructor that accepts a radius and sets it to the radius


variable

public Circle(double radius) {

[Link] = radius;

// Override the calculateArea method to compute the area of the


circle

@Override

double calculateArea() {

// Return the area using the formula π * radius^2

return [Link] * radius * radius;

// Override the calculatePerimeter method to compute the perimeter


of the circle

@Override

double calculatePerimeter() {

// Return the perimeter using the formula 2 * π * radius

return 2 * [Link] * radius;

// [Link]

// Define a subclass named Triangle that extends Shape

class Triangle extends Shape {


// Declare private double variables to store the sides of the
triangle

private double side1;

private double side2;

private double side3;

// Constructor that accepts three sides and sets them to the


corresponding variables

public Triangle(double side1, double side2, double side3) {

this.side1 = side1;

this.side2 = side2;

this.side3 = side3;

// Override the calculateArea method to compute the area of the


triangle

@Override

double calculateArea() {

// Calculate the semi-perimeter

double s = (side1 + side2 + side3) / 2;

// Return the area using Heron's formula

return [Link](s * (s - side1) * (s - side2) * (s - side3));

// Override the calculatePerimeter method to compute the perimeter


of the triangle

@Override

double calculatePerimeter() {

// Return the perimeter by summing up all the sides

return side1 + side2 + side3;

}
// [Link]

// Define the Main class

public class Main {

// Main method to run the program

public static void main(String[] args) {

// Declare and initialize the radius for the circle

double r = 4.0;

// Create an instance of Circle with the specified radius

Circle circle = new Circle(r);

// Declare and initialize the sides for the triangle

double ts1 = 3.0, ts2 = 4.0, ts3 = 5.0;

// Create an instance of Triangle with the specified sides

Triangle triangle = new Triangle(ts1, ts2, ts3);

// Print the radius of the circle

[Link]("Radius of the Circle: " + r);

// Print the area of the circle by calling the calculateArea


method

[Link]("Area of the Circle: " +


[Link]());

// Print the perimeter of the circle by calling the


calculatePerimeter method

[Link]("Perimeter of the Circle: " +


[Link]());

// Print the sides of the triangle

[Link]("\nSides of the Triangle are: " + ts1 +


',' + ts2 + ',' + ts3);

// Print the area of the triangle by calling the calculateArea


method
[Link]("Area of the Triangle: " +
[Link]());

// Print the perimeter of the triangle by calling the


calculatePerimeter method

[Link]("Perimeter of the Triangle: " +


[Link]());

Output:
Radius of the Circle4.0
Area of the Circle: 50.26548245743669
Perimeter of the Circle: 25.132741228718345

Sides of the Triangle are: 3.0,4.0,5.0


Area of the Triangle: 6.0
Perimeter of the Triangle: 12.0
Exercise - 5
a) Write a JAVA program give example for “super” keyword.

Sample1:

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:

Compile by: javac [Link]

Run by: java TestSuper1

black
white

Sample2:

The super keyword in Java is used to refer to the immediate parent class object. It is often used
to access methods and constructors of the parent class from a child class. Below is an example
program that demonstrates the use of the super keyword in various contexts.

Java Program: Using the super Keyword


// Parent class (Super class)
class Animal {
String name;

// Constructor of the Animal class


Animal(String name) {
[Link] = name;
}
// Method in the Animal class
void displayInfo() {
[Link]("Animal: " + name);
}
}

// Child class (Sub class) inheriting from Animal


class Dog extends Animal {
String breed;

// Constructor of the Dog class


Dog(String name, String breed) {
// Call the constructor of the parent class (Animal)
super(name);
[Link] = breed;
}

// Method in the Dog class


void displayInfo() {
// Call the displayInfo method of the parent class
[Link]();
[Link]("Breed: " + breed);
}

// Method to demonstrate super keyword in accessing parent class method


void makeSound() {
[Link]("The dog barks.");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Dog class
Dog myDog = new Dog("Buddy", "Golden Retriever");

// Call the displayInfo method (will use super to access parent


method)
[Link]();

// Call the makeSound method


[Link]();
}
}

Explanation:

1. Parent Class (Animal):


o The Animal class has a field name and a constructor that initializes this field.
o The displayInfo() method prints the name of the animal.
2. Child Class (Dog):
o The Dog class extends the Animal class and adds a new field breed.
o The Dog constructor takes two parameters (name and breed). It uses
super(name) to call the constructor of the Animal class, passing the name to it.
This initializes the name field in the parent class.
o The displayInfo() method in the Dog class overrides the displayInfo()
method in the Animal class. Inside this method, [Link]() is used
to call the displayInfo() method of the Animal class, allowing it to print the
name. The method then prints the breed of the dog.
o The makeSound() method prints a message indicating the dog's sound.
3. Main Class (Main):
o Inside the main method, an object of the Dog class (myDog) is created with the
name "Buddy" and breed "Golden Retriever".
o The displayInfo() method is called on myDog, demonstrating how the super
keyword is used to invoke the parent class method.
o The makeSound() method is also called to show additional functionality of the
Dog class.

Output:

When you run this program, you will get the following output:

Animal: Buddy
Breed: Golden Retriever
The dog barks.

This example demonstrates the use of the super keyword in Java:

 To call the constructor of the parent class (super(name)).


 To call a method of the parent class from a method in the child class
([Link]()).

b) Write a JAVA program to implement Interface. What kind of Inheritance can be


achieved?

Sample1:

// Java program to demonstrate that a class can


// implement multiple interfaces
import [Link].*;

interface intfA {
void m1();
}

interface intfB {
void m2();
}

// class implements both interfaces


// and provides implementation to the method.
class sample implements intfA, intfB {
@Override public void m1()
{
[Link]("Welcome: inside the method m1");
}

@Override public void m2()


{
[Link]("Welcome: inside the method m2");
}
}

class GFG {
public static void main(String[] args)
{
sample ob1 = new sample();

// calling the method implemented


// within the class.
ob1.m1();
ob1.m2();
}
}

Output:
Welcome: inside the method m1
Welcome: inside the method m2

Sample2:

In Java, an interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot contain
instance fields or constructors. They are implemented by classes and extended by other
interfaces.

Interfaces are a key mechanism in Java for achieving multiple inheritance. While a class can
inherit from only one superclass (single inheritance), it can implement multiple interfaces,
thereby achieving multiple inheritance of type.

Java Program: Implementing an Interface


// Interface definition
interface Shape {
// Abstract method to calculate the area
double calculateArea();

// Abstract method to calculate the perimeter


double calculatePerimeter();
}

// Class implementing the Shape interface


class Rectangle implements Shape {
double length, width;

// Constructor for Rectangle


Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}

// Implementing the calculateArea method


@Override
public double calculateArea() {
return length * width;
}

// Implementing the calculatePerimeter method


@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}

// Class implementing the Shape interface


class Circle implements Shape {
double radius;

// Constructor for Circle


Circle(double radius) {
[Link] = radius;
}

// Implementing the calculateArea method


@Override
public double calculateArea() {
return [Link] * radius * radius;
}

// Implementing the calculatePerimeter method


@Override
public double calculatePerimeter() {
return 2 * [Link] * radius;
}
}

public class Main {


public static void main(String[] args) {
// Create a Rectangle object
Shape rectangle = new Rectangle(5, 7);
[Link]("Rectangle Area: " + [Link]());
[Link]("Rectangle Perimeter: " +
[Link]());

// Create a Circle object


Shape circle = new Circle(3.5);
[Link]("Circle Area: " + [Link]());
[Link]("Circle Perimeter: " +
[Link]());
}
}
Explanation:

1. Interface Definition (Shape):


o The Shape interface declares two abstract methods: calculateArea() and
calculatePerimeter().
o Any class that implements this interface must provide implementations for these
methods.
2. Class Implementing the Interface (Rectangle):
o The Rectangle class implements the Shape interface.
o It provides concrete implementations of the calculateArea() and
calculatePerimeter() methods, using its own length and width fields.
3. Another Class Implementing the Interface (Circle):
o The Circle class also implements the Shape interface.
o It provides its own implementations of the calculateArea() and
calculatePerimeter() methods, using its own radius field.
4. Main Class (Main):
o Inside the main method, instances of Rectangle and Circle are created.
o The calculateArea() and calculatePerimeter() methods are called on
these objects, demonstrating polymorphism.

Output:

When you run this program, you will get the following output:

Rectangle Area: 35.0


Rectangle Perimeter: 24.0
Circle Area: 38.48451000647496
Circle Perimeter: 21.991148575128552

Inheritance in Interfaces:

 Multiple Inheritance: Java classes cannot inherit from multiple classes (no multiple
inheritance for classes), but they can implement multiple interfaces. This allows a class
to inherit behavior from multiple sources, achieving multiple inheritance in a way that
avoids the complexities of multiple class inheritance.

interface A {
void methodA();
}

interface B {
void methodB();
}

class C implements A, B {
@Override
public void methodA() {
[Link]("Method A");
}

@Override
public void methodB() {
[Link]("Method B");
}
}

 Interface Inheritance: Interfaces can also inherit from other interfaces, allowing them
to be combined and extended.

interface A {
void methodA();
}

interface B extends A {
void methodB();
}

class C implements B {
@Override
public void methodA() {
[Link]("Method A");
}

@Override
public void methodB() {
[Link]("Method B");
}
}

Conclusion:

 Single Inheritance of Classes: A class can only inherit (extend) one other class.
 Multiple Inheritance via Interfaces: A class can implement multiple interfaces,
thereby achieving multiple inheritance.
 Interface Inheritance: Interfaces themselves can extend multiple other interfaces.

This flexibility allows Java to support multiple inheritance patterns through interfaces while
avoiding the pitfalls of multiple class inheritance.

c) Write a JAVA program that implements Runtime polymorphism.

Sample1:

class Animal {
public void move() {
[Link]("Animals can move");
}
}
class Dog extends Animal {
public void move() {
[Link]("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
[Link](); // runs the method in Animal class
[Link](); // runs the method in Dog class
}
}
Output

This will produce the following result −

Animals can move


Dogs can walk and run

Sample2:

Runtime polymorphism in Java is achieved through method overriding. It allows a subclass to


provide a specific implementation of a method that is already defined in its superclass. The
method to be executed is determined at runtime, based on the object being referred to.

Here’s a Java program that demonstrates runtime polymorphism:

Java Program: Runtime Polymorphism


// Superclass (Parent class)
class Animal {
// Method in the superclass
void sound() {
[Link]("The animal makes a sound.");
}
}

// Subclass (Child class) Dog inherits Animal


class Dog extends Animal {
// Overriding the sound method
@Override
void sound() {
[Link]("The dog barks.");
}
}

// Subclass (Child class) Cat inherits Animal


class Cat extends Animal {
// Overriding the sound method
@Override
void sound() {
[Link]("The cat meows.");
}
}

// Subclass (Child class) Cow inherits Animal


class Cow extends Animal {
// Overriding the sound method
@Override
void sound() {
[Link]("The cow moos.");
}
}

public class Main {


public static void main(String[] args) {
// Creating objects of different subclasses
Animal myAnimal = new Animal(); // Parent reference to Parent object
Animal myDog = new Dog(); // Parent reference to Child object
Animal myCat = new Cat(); // Parent reference to Child object
Animal myCow = new Cow(); // Parent reference to Child object

// Calling the sound method on each object


[Link](); // Calls the method in Animal class
[Link](); // Calls the overridden method in Dog class
[Link](); // Calls the overridden method in Cat class
[Link](); // Calls the overridden method in Cow class
}
}

Explanation:
1. Superclass (Animal):
o The Animal class has a method sound() that prints a generic message indicating that the
animal makes a sound.
2. Subclasses (Dog, Cat, Cow):
o The Dog, Cat, and Cow classes each extend the Animal class and override the sound()
method to provide a specific implementation for the type of sound each animal makes.
3. Main Class (Main):
o In the main method, objects of type Animal, Dog, Cat, and Cow are created. However, the
Dog, Cat, and Cow objects are referred to by a reference variable of type Animal.
o The sound() method is called on each object. At runtime, Java determines which method to
call based on the actual object that the reference variable is pointing to.

Output:

When you run this program, you will get the following output:
The animal makes a sound.
The dog barks.
The cat meows.
The cow moos.

Key Concepts:

 Method Overriding: The Dog, Cat, and Cow classes each override the sound() method of the
Animal class to provide a specific implementation.
 Upcasting: In the main method, Dog, Cat, and Cow objects are treated as objects of type Animal. This
is known as upcasting.
 Runtime Polymorphism: The method that gets executed is determined at runtime based on the actual
object type that the reference variable points to, rather than the reference type itself.

Conclusion:

Runtime polymorphism allows Java to dynamically determine which method to call based on
the object at runtime, enabling more flexible and maintainable code. This is a powerful feature
of object-oriented programming in Java.
Exercise - 6
a) Write a JAVA program that describes exception handling mechanism

Sample1:

In Java, the exception handling mechanism is used to manage runtime errors and maintain the
normal flow of the program. This is done using five keywords: try, catch, finally, throw,
and throws.

Here's a basic Java program demonstrating exception handling:

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
// Code that may throw an exception
int division = divideNumbers(10, 0);
[Link]("Result: " + division);
} catch (ArithmeticException e) {
// Handling the specific ArithmeticException
[Link]("Error: Cannot divide by zero!");
} catch (Exception e) {
// Handling any other exception
[Link]("An error occurred: " + [Link]());
} finally {
// Code that will always execute, regardless of exceptions
[Link]("Finally block executed.");
}
[Link]("Program continues after exception handling.");
}
// Method that throws an ArithmeticException if division by zero occurs
public static int divideNumbers(int numerator, int denominator) throws
ArithmeticException {
return numerator / denominator;
}
}

Explanation:

1. try Block: The code that may throw an exception is written inside the try block. In
this case, we're attempting to divide a number by zero, which will cause an
ArithmeticException.
2. catch Block: The catch block handles the exception. We have two catch blocks here:
o One for ArithmeticException, which specifically handles division by zero.
o Another generic catch block that handles any other type of exception.
3. finally Block: The finally block contains code that will run whether an exception
occurs or not. This is typically used for cleanup activities like closing resources (e.g.,
file streams, database connections).
4. throws Keyword: The method divideNumbers() declares that it may throw an
ArithmeticException. This informs the caller to handle the exception.
5. Normal Flow: After the exception is handled, the program continues its normal
execution.
Output:
Error: Cannot divide by zero!
Finally block executed.
Program continues after exception handling.

This demonstrates how exceptions can be caught and handled, allowing the program to
continue running smoothly even after an error occurs.

Sample2:

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

Output:

Exception in thread main [Link]:/ by zero


rest of the code...
b) Write a JAVA program Illustrating Multiple catch clauses

Sample1:

In Java, multiple catch clauses can be used to handle different types of exceptions that may be
thrown by a block of code. When an exception is thrown, Java looks for the first catch block
that can handle it. Once a matching catch block is found, the remaining catch blocks are
ignored.

Here's an example program illustrating multiple catch clauses:

public class MultipleCatchExample {


public static void main(String[] args) {
try {
// Code that may throw multiple types of exceptions
int[] numbers = {1, 2, 3};
[Link]("Accessing element: " + numbers[5]); // May
cause ArrayIndexOutOfBoundsException

int result = divideNumbers(10, 0); // May cause


ArithmeticException
[Link]("Result: " + result);

} catch (ArrayIndexOutOfBoundsException e) {
// Handling the specific ArrayIndexOutOfBoundsException
[Link]("Error: Array index is out of bounds!");

} catch (ArithmeticException e) {
// Handling the specific ArithmeticException
[Link]("Error: Cannot divide by zero!");

} catch (Exception e) {
// Handling any other general exception
[Link]("An unexpected error occurred: " +
[Link]());
}

[Link]("Program continues after exception handling.");


}

// Method that throws an ArithmeticException if division by zero occurs


public static int divideNumbers(int numerator, int denominator) throws
ArithmeticException {
return numerator / denominator;
}
}

Explanation:

1. try Block: The try block contains code that might throw multiple types of exceptions:
o Accessing an invalid index in the array may cause an
ArrayIndexOutOfBoundsException.
o Dividing a number by zero may cause an ArithmeticException.
2. Multiple catch Blocks:
o The first catch block handles the ArrayIndexOutOfBoundsException.
o The second catch block handles the ArithmeticException.
o The third catch block is a general one that catches any other exceptions that are
not specifically handled by the previous blocks.
3. Normal Flow: After handling the exceptions, the program continues its normal
execution.

Output:
Error: Array index is out of bounds!
Program continues after exception handling.

In this case, the ArrayIndexOutOfBoundsException occurs, and it's handled by the


corresponding catch block. The program then continues executing the rest of the code. The
ArithmeticException doesn't occur because the first exception interrupts the try block, but
if the array access were valid, the division by zero would trigger the second catch block.

This demonstrates how multiple catch clauses can be used to handle different types of
exceptions in a program.

Sample2:

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}

Output:

Arithmetic Exception occurs


rest of the code

c) Write a JAVA program for creation of Java Built-in Exceptions.

Java provides a rich set of built-in exceptions, which are part of the [Link] package. These
exceptions are used to handle various error conditions that occur during program execution.
Some commonly used built-in exceptions include:

 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 NumberFormatException

Below is a Java program that demonstrates the creation and handling of some of these built-in
exceptions:

public class BuiltInExceptionExample {


public static void main(String[] args) {
// Example 1: ArithmeticException
try {
int result = 10 / 0; // Division by zero causes
ArithmeticException
} catch (ArithmeticException e) {
[Link]("Caught an ArithmeticException: " +
[Link]());
}

// Example 2: NullPointerException
try {
String str = null;
[Link]([Link]()); // Accessing null object
causes NullPointerException
} catch (NullPointerException e) {
[Link]("Caught a NullPointerException: " +
[Link]());
}

// Example 3: ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // Accessing invalid array index
causes ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught an ArrayIndexOutOfBoundsException: "
+ [Link]());
}

// Example 4: NumberFormatException
try {
String invalidNumber = "abc";
int number = [Link](invalidNumber); // Invalid string
format causes NumberFormatException
} catch (NumberFormatException e) {
[Link]("Caught a NumberFormatException: " +
[Link]());
}

[Link]("Program continues after handling built-in


exceptions.");
}
}

Explanation:

1. ArithmeticException:
o Occurs when an arithmetic operation, such as division by zero, is performed. In
this example, the statement 10 / 0 causes an ArithmeticException.

2. NullPointerException:
o Occurs when there is an attempt to use an object reference that has not been
initialized (i.e., it is null). In this example, accessing the length of a null string
causes a NullPointerException.
3. ArrayIndexOutOfBoundsException:
o Occurs when trying to access an array element with an index that is out of the
valid range. In this example, trying to access the element at index 5 of a 3-
element array causes an ArrayIndexOutOfBoundsException.
4. NumberFormatException:
o Occurs when an attempt is made to convert a string to a numeric type, but the
string does not have the appropriate format. In this example, trying to parse the
string "abc" as an integer causes a NumberFormatException.

Output:
Caught an ArithmeticException: / by zero
Caught a NullPointerException: Cannot invoke "[Link]()" because "str"
is null
Caught an ArrayIndexOutOfBoundsException: Index 5 out of bounds for length
3
Caught a NumberFormatException: For input string: "abc"
Program continues after handling built-in exceptions.

This program demonstrates how Java's built-in exceptions are thrown and caught. Each try
block contains code that triggers a specific type of built-in exception, and each exception is
handled in its corresponding catch block, allowing the program to continue running.

Reference: [Link]
d) Write a JAVA program for creation of User Defined Exception

In Java, you can create user-defined (custom) exceptions by extending the Exception class
(for checked exceptions) or the RuntimeException class (for unchecked exceptions). Custom
exceptions are useful when you want to represent specific error conditions that are not covered
by Java's built-in exceptions.

Here's a Java program that demonstrates the creation of a user-defined exception:

Example: Creating a Custom Exception for Age Validation


// Step 1: Create a User-Defined Exception class by extending the Exception
class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message); // Pass the message to the superclass constructor
}
}

public class UserDefinedExceptionExample {


// Method to validate the age of a user
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
// If age is less than 18, throw the custom InvalidAgeException
throw new InvalidAgeException("Age is not valid for voting. Must
be 18 or older.");
} else {
[Link]("Age is valid. You are allowed to vote.");
}
}

public static void main(String[] args) {


try {
// Test with an invalid age
validateAge(16); // This will throw the InvalidAgeException
} catch (InvalidAgeException e) {
// Catch the custom exception and display the error message
[Link]("Caught the exception: " + [Link]());
}

[Link]("Program continues after handling the custom


exception.");
}
}

Explanation:

1. Creating the Custom Exception:


o A user-defined exception class InvalidAgeException is created by extending
the Exception class.
o The constructor of InvalidAgeException takes a message as a parameter and
passes it to the superclass constructor (Exception), which is used to set the
exception message.
2. Method validateAge():
o This method checks whether the input age is valid for voting (i.e., 18 or older).
o If the age is less than 18, it throws an instance of the InvalidAgeException
with a custom error message.
3. Using the Custom Exception:
o In the main() method, we call the validateAge() method with an invalid age
(16).
o The InvalidAgeException is caught in the catch block, and the custom
message is printed to the console.

Output:
Caught the exception: Age is not valid for voting. Must be 18 or older.
Program continues after handling the custom exception.

This program demonstrates the creation and usage of a user-defined exception. You can create
similar exceptions tailored to your specific needs, making your error handling more meaningful
and understandable within the context of your application.
Exercise - 7
a) Write a JAVA program that creates threads by extending Thread [Link] 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)

Here’s how you can create threads in Java by both extending the Thread class and
implementing the Runnable interface. This example demonstrates how to run multiple threads
concurrently, each printing a message at different intervals.

1. Creating Threads by Extending the Thread Class

In this approach, each thread class extends the Thread class and overrides the run() method
to define the thread's behavior.

// Thread class that prints "Good Morning" every 1 second


class GoodMorningThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

// Thread class that prints "Hello" every 2 seconds


class HelloThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

// Thread class that prints "Welcome" every 3 seconds


class WelcomeThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000); // Sleep for 3 seconds
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
public class ExtendThreadExample {
public static void main(String[] args) {
// Create thread instances
GoodMorningThread t1 = new GoodMorningThread();
HelloThread t2 = new HelloThread();
WelcomeThread t3 = new WelcomeThread();

// Start the threads


[Link]();
[Link]();
[Link]();
}
}

2. Creating Threads by Implementing the Runnable Interface

In this approach, the thread behavior is defined in a class that implements the Runnable
interface, and threads are created by passing instances of these classes to Thread objects.

// Runnable class that prints "Good Morning" every 1 second


class GoodMorningRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000); // Sleep for 1 second
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

// Runnable class that prints "Hello" every 2 seconds


class HelloRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000); // Sleep for 2 seconds
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

// Runnable class that prints "Welcome" every 3 seconds


class WelcomeRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000); // Sleep for 3 seconds
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

public class RunnableExample {


public static void main(String[] args) {
// Create Runnable instances
Runnable r1 = new GoodMorningRunnable();
Runnable r2 = new HelloRunnable();
Runnable r3 = new WelcomeRunnable();

// Create threads by passing Runnable instances


Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
Thread t3 = new Thread(r3);

// Start the threads


[Link]();
[Link]();
[Link]();
}
}

Explanation:

1. Extending Thread Class:


o Each class (GoodMorningThread, HelloThread, WelcomeThread) extends the
Thread class and overrides the run() method.
o Inside the run() method, each thread continuously prints a message and then
sleeps for a specific duration (1000ms, 2000ms, 3000ms respectively).
2. Implementing Runnable Interface:
o Each class (GoodMorningRunnable, HelloRunnable, WelcomeRunnable)
implements the Runnable interface and defines the run() method.
o Thread objects are created by passing instances of these Runnable classes to the
Thread constructor.
3. Starting the Threads:
o In both approaches, the threads are started using the start() method, which
internally calls the run() method in a new thread of execution.

Output:

Both programs will print the following output concurrently (in no specific order due to thread
scheduling):

Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
...

The messages will continue to be printed at intervals of 1 second for "Good Morning", 2
seconds for "Hello", and 3 seconds for "Welcome".
Key Differences:

 Extending Thread: Provides direct inheritance from the Thread class, but limits
further inheritance as Java doesn’t support multiple inheritance.
 Implementing Runnable: More flexible, as the class can still extend another class
while implementing Runnable. This is the preferred approach in multi-threaded
programming.

b) Write a program illustrating isAlive and join ()

In Java, the isAlive() method is used to check whether a thread is still running, and the
join() method is used to wait for a thread to finish its execution. These two methods are often
used together to ensure that a program waits for specific threads to complete before continuing
with its execution.

Here is a Java program that illustrates the usage of isAlive() and join():

class MyThread extends Thread {


private String message;

public MyThread(String message) {


[Link] = message;
}

public void run() {


for (int i = 1; i <= 5; i++) {
[Link](message + " - " + i);
try {
[Link](500); // Sleep for 500ms
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
}

public class ThreadExample {


public static void main(String[] args) {
// Create thread instances
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
MyThread t3 = new MyThread("Thread 3");

// Start the threads


[Link]();
[Link]();
[Link]();

// Use isAlive() method to check if threads are alive


[Link]("Is Thread 1 alive? " + [Link]());
[Link]("Is Thread 2 alive? " + [Link]());
[Link]("Is Thread 3 alive? " + [Link]());

// Use join() method to wait for threads to finish


try {
[Link](); // Wait for Thread 1 to finish
[Link](); // Wait for Thread 2 to finish
[Link](); // Wait for Thread 3 to finish
} catch (InterruptedException e) {
[Link]([Link]());
}

// After all threads have finished


[Link]("Is Thread 1 alive after join? " + [Link]());
[Link]("Is Thread 2 alive after join? " + [Link]());
[Link]("Is Thread 3 alive after join? " + [Link]());

[Link]("All threads have finished execution.");


}
}

Explanation:

1. Thread Creation:
o We define a MyThread class that extends Thread and overrides the run()
method.
o In the run() method, the thread prints a message 5 times, pausing for 500
milliseconds between each print.
2. Starting Threads:
o In the main() method, we create and start three threads (t1, t2, t3).
3. Using isAlive():
o After starting the threads, we use the isAlive() method to check whether each
thread is still running. This method returns true if the thread is alive (still
running or in a runnable state) and false if it has completed execution.
4. Using join():
o We then use the join() method to wait for each thread to finish its execution.
This ensures that the main() thread waits for t1, t2, and t3 to complete before
proceeding.
o join() is particularly useful when you need to ensure that one or more threads
complete before continuing with the rest of the program.
5. Final isAlive() Check:
o After using join(), we again check the status of each thread using isAlive().
At this point, all threads should have finished, so isAlive() should return
false.

Output:
Thread 1 - 1
Thread 2 - 1
Thread 3 - 1
Is Thread 1 alive? true
Is Thread 2 alive? true
Is Thread 3 alive? true
Thread 1 - 2
Thread 2 - 2
Thread 3 - 2
Thread 1 - 3
Thread 2 - 3
Thread 3 - 3
Thread 1 - 4
Thread 2 - 4
Thread 3 - 4
Thread 1 - 5
Thread 2 - 5
Thread 3 - 5
Is Thread 1 alive after join? false
Is Thread 2 alive after join? false
Is Thread 3 alive after join? false
All threads have finished execution.

Key Points:

 isAlive(): This method checks if a thread is still running.


 join(): This method allows one thread to wait for the completion of another thread.
The main() thread waits for t1, t2, and t3 to finish before continuing.

This program illustrates how to manage thread lifecycle using isAlive() and join() in Java,
ensuring proper synchronization between threads.

c) Write a Program illustrating Daemon Threads.

In Java, daemon threads are low-priority threads that run in the background to perform tasks
such as garbage collection. They differ from user threads in that the JVM automatically exits
when only daemon threads are running. You can create a daemon thread by using the
setDaemon(true) method on a Thread object.

Here’s a Java program that demonstrates daemon threads:

Example: Daemon Thread vs. User Thread


class MyDaemonThread extends Thread {
public void run() {
while (true) {
[Link]("Daemon thread is running...");
try {
[Link](1000); // Sleep for 1 second
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}
}

class MyUserThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("User thread execution: " + i);
try {
[Link](1500); // Sleep for 1.5 seconds
} catch (InterruptedException e) {
[Link]([Link]());
}
}
[Link]("User thread finished.");
}
}
public class DaemonThreadExample {
public static void main(String[] args) {
MyDaemonThread daemonThread = new MyDaemonThread();
MyUserThread userThread = new MyUserThread();

// Set the daemon thread


[Link](true);

// Start both threads


[Link]();
[Link]();

try {
// Wait for the user thread to finish
[Link]();
} catch (InterruptedException e) {
[Link]([Link]());
}

// After the user thread finishes, the program will exit,


// and the daemon thread will be terminated automatically.
[Link]("Main thread finished, JVM will exit.");
}
}

Explanation:

1. Daemon Thread (MyDaemonThread):


o This thread runs indefinitely, printing a message every second. It is marked as
a daemon thread using the setDaemon(true) method before starting.
o Daemon threads run in the background and do not prevent the JVM from
exiting.
2. User Thread (MyUserThread):
o This thread runs a loop five times, printing a message every 1.5 seconds. It
represents a user thread, which is a regular thread that keeps the JVM alive until
it finishes its execution.
3. Thread Management:
o Both threads are started using the start() method.
o The main() thread waits for the userThread to finish using the join() method.
o Once the user thread completes its execution, the program finishes, and the JVM
automatically terminates the daemon thread.

Output:
Daemon thread is running...
User thread execution: 1
Daemon thread is running...
User thread execution: 2
Daemon thread is running...
User thread execution: 3
Daemon thread is running...
User thread execution: 4
Daemon thread is running...
User thread execution: 5
User thread finished.
Main thread finished, JVM will exit.
Key Points:

1. Daemon Thread: The daemon thread (MyDaemonThread) runs indefinitely, printing a


message every second. However, once the userThread finishes and the main() thread
exits, the daemon thread is automatically terminated, and the JVM exits.
2. User Thread: The user thread (MyUserThread) runs a finite number of times (5
iterations). Since this is a user thread, the JVM will wait for this thread to finish before
terminating.
3. Daemon Behavior: Daemon threads are useful for background tasks that should not
prevent the JVM from exiting. They are automatically terminated when no other user
threads are running.

In this program, the daemon thread will not complete its task because it is forcibly terminated
when the JVM exits.

d) Write a JAVA program Producer Consumer Problem

The Producer-Consumer problem is a classic synchronization problem where two threads


(producer and consumer) share a common fixed-size buffer. The producer's job is to generate
data and put it into the buffer, while the consumer's job is to consume the data from the buffer.
The problem is to ensure that the producer does not add data when the buffer is full, and the
consumer does not remove data when the buffer is empty.

In Java, this problem can be solved using thread synchronization techniques such as wait()
and notify(). Below is an example implementation of the Producer-Consumer problem:

Producer-Consumer Problem using wait() and notify()


import [Link];
import [Link];

class Buffer {
private final int MAX_SIZE = 5; // Maximum size of the buffer
private Queue<Integer> queue = new LinkedList<>();

// Method for the producer to add data to the buffer


public synchronized void produce(int value) throws InterruptedException
{
while ([Link]() == MAX_SIZE) {
[Link]("Buffer is full, producer is waiting...");
wait(); // Wait until there is space in the buffer
}
[Link](value);
[Link]("Produced: " + value);
notify(); // Notify the consumer that new data is available
}

// Method for the consumer to consume data from the buffer


public synchronized int consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer is empty, consumer is waiting...");
wait(); // Wait until there is data in the buffer
}
int value = [Link]();
[Link]("Consumed: " + value);
notify(); // Notify the producer that there is space in the buffer
return value;
}
}

class Producer implements Runnable {


private Buffer buffer;

public Producer(Buffer buffer) {


[Link] = buffer;
}

@Override
public void run() {
int value = 0;
try {
while (true) {
[Link](value++); // Produce an incrementing value
[Link](500); // Simulate production time
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

class Consumer implements Runnable {


private Buffer buffer;

public Consumer(Buffer buffer) {


[Link] = buffer;
}

@Override
public void run() {
try {
while (true) {
[Link](); // Consume a value from the buffer
[Link](1000); // Simulate consumption time
}
} catch (InterruptedException e) {
[Link]([Link]());
}
}
}

public class ProducerConsumerExample {


public static void main(String[] args) {
Buffer buffer = new Buffer();

// Create producer and consumer threads


Thread producerThread = new Thread(new Producer(buffer));
Thread consumerThread = new Thread(new Consumer(buffer));

// Start the threads


[Link]();
[Link]();
}
}
Explanation:

1. Buffer Class:
o This class acts as the shared buffer between the producer and consumer. It uses
a Queue to store the produced data. The buffer has a maximum size of 5.
o The produce() method is synchronized and adds data to the buffer. If the buffer
is full, the producer thread waits until space is available.
o The consume() method is also synchronized and removes data from the buffer.
If the buffer is empty, the consumer thread waits until data is available.
o Both methods use wait() and notify() to coordinate the actions of the
producer and consumer threads.
2. Producer Class:
o This class implements Runnable and produces data. It continuously adds
incrementing integer values to the buffer and waits for 500 milliseconds
between productions to simulate production time.
3. Consumer Class:
o This class also implements Runnable and consumes data from the buffer. It
waits for 1000 milliseconds between consumptions to simulate consumption
time.
4. Main Class:
o The ProducerConsumerExample class creates and starts the producer and
consumer threads.

Output Example:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Consumed: 1
Produced: 4
Buffer is full, producer is waiting...
Consumed: 2
Produced: 5
Buffer is empty, consumer is waiting...

Key Concepts:

 Synchronization: The synchronized keyword is used to ensure that only one thread
can access the buffer at a time.
 wait() and notify(): The producer and consumer threads use wait() to pause their
execution when necessary and notify() to wake up the other thread when the buffer's
state changes (full/empty).
 Concurrency Control: The program controls the concurrent execution of producer and
consumer threads to avoid race conditions and ensure proper synchronization.

This solution effectively solves the Producer-Consumer problem by coordinating the actions
of the producer and consumer using synchronization primitives.
Exercise – 8
a) Write a JAVA program that import and use the user defined packages

In Java, user-defined packages allow you to organize your classes logically. You can create a
package, define classes within it, and then use those classes in another program by importing
the package.

Here’s an example that demonstrates how to create a user-defined package and use it in a Java
program.

Step 1: Create a User-Defined Package

Let's create a package named mypackage that contains a class called MyClass.

1. Create a directory called mypackage.


2. Inside this directory, create a file named [Link].

// File: mypackage/[Link]
package mypackage;

public class MyClass {


public void displayMessage() {
[Link]("Hello from MyClass in mypackage!");
}
}

Step 2: Create a Java Program that Uses the User-Defined Package

Now, create another Java program outside of the mypackage directory that imports and uses
MyClass.

// File: [Link]
import [Link];

public class Main {


public static void main(String[] args) {
// Create an instance of MyClass
MyClass myObject = new MyClass();

// Call the displayMessage() method


[Link]();
}
}

Directory Structure:

Your directory structure should look like this:

├── mypackage
│ └── [Link]
└── [Link]
Step 3: Compile and Run the Program

1. Compile the Package Class: Navigate to the root directory (the directory containing
mypackage and [Link]), and compile the [Link] file.

bash
Copy code
javac mypackage/[Link]

2. Compile the Main Class: Now compile the [Link] file.

bash
Copy code
javac [Link]

3. Run the Program: Finally, run the Main class. The JVM will automatically locate the
MyClass class from the mypackage package.

bash
Copy code
java Main

Output:
Hello from MyClass in mypackage!

Explanation:

1. Creating the Package:


o The MyClass class is placed inside the mypackage package. The package
mypackage; statement at the top of the file indicates that the class belongs to
this package.
2. Importing the Package:
o In the [Link] file, we import the MyClass class from the mypackage
package using the import [Link]; statement.
o We then create an instance of MyClass and call its displayMessage() method.
3. Compiling and Running:
o When compiling the program, you need to compile the classes in the correct
order: first, the classes in the package, then the classes that use the package.
o Running the Main class correctly invokes the method from the user-defined
package.

This is a simple demonstration of how to create and use user-defined packages in Java. It allows
you to organize your code better and avoid naming conflicts by grouping related classes into
packages.
b) Without writing any code, build a GUI that display text in label and image in an
ImageView (use JavaFX)

To build a simple GUI in JavaFX that displays text in a Label and an image in an ImageView,
follow these conceptual steps:

Steps to Build GUI (No Code):

1. Set Up JavaFX Project:


o Ensure you have JavaFX set up in your IDE (e.g., IntelliJ, Eclipse).
o Include the required JavaFX libraries in your project.
2. Create the Primary Stage and Scene:
o Start by creating a Stage which serves as the main window.
o Inside the Stage, create a Scene that holds all the GUI components.
3. Design the Layout:
o Use a layout container (such as VBox or HBox) to arrange the Label and
ImageView vertically or horizontally.
 VBox Layout: Arranges nodes in a vertical column.
 HBox Layout: Arranges nodes in a horizontal row.
o The layout will serve as the root node of your scene.
4. Add Text to the Label:
o Create a Label node to display the desired text.
o Set the text content in the label.
5. Add Image to the ImageView:
o Create an Image object by loading an image file from resources or a URL.
o Pass the Image object to the ImageView to display the image.
6. Add Components to Layout:
o Add both the Label and the ImageView to the chosen layout container (e.g.,
VBox or HBox).
7. Set the Scene and Show the Stage:
o Set the scene with the layout as the root node to the primary stage.
o Display the stage using the show() method.

Visual Breakdown:

 Stage (Window)
o Scene (Container for UI components)
 VBox or HBox (Layout container)
 Label (Text display)
 ImageView (Image display)

Example Structure:

1. Stage: The main window of the application.


2. Scene: Holds the layout of the components.
3. VBox Layout:
o Label: Displays the text.
o ImageView: Displays the image.
This conceptual framework gives you a step-by-step guide to building a simple JavaFX
application that displays text and an image.

c) Build a Tip Calculator app using several JavaFX components and learn how to respond
to user interactions with the GUI

Building a Tip Calculator app in JavaFX will involve creating a GUI that allows the user to
input a bill amount, select a tip percentage, and calculate the total amount including the tip.
This project will introduce you to several JavaFX components such as TextField, ComboBox,
Button, and Label, and show how to handle user interactions.

Steps to Build the Tip Calculator App

1. Set Up JavaFX Project:


o Ensure you have JavaFX properly configured in your IDE (e.g., IntelliJ,
Eclipse).
o Add the necessary JavaFX libraries to your project.
2. Design the GUI Layout:
o GridPane Layout: Use a GridPane layout to organize the UI components in a
grid-like structure (rows and columns).
3. Components:
o Label: For displaying instructions like "Enter Bill Amount", "Select Tip
Percentage", etc.
o TextField: For user input to enter the bill amount.
o ComboBox: For selecting the tip percentage (e.g., 10%, 15%, 20%).
o Button: For triggering the calculation of the total amount.
o Label: To display the result (total amount including tip).
4. Handle User Interactions:
o Use event handling to respond to button clicks and calculate the tip.
o Get user input from TextField and ComboBox.
o Calculate the total amount when the "Calculate" button is clicked.
o Display the result in a Label.

GUI Structure

 Stage (Main Window)


o Scene (Container for UI components)
 GridPane (Layout)
 Row 1:
 Label: "Enter Bill Amount"
 TextField: For entering the bill amount
 Row 2:
 Label: "Select Tip Percentage"
 ComboBox: For selecting the tip percentage
 Row 3:
 Button: "Calculate Tip"
 Row 4:
 Label: "Total Amount" (Displays the result)

Detailed Design Steps:

1. Create the Main Application Class:


o Extend the Application class and override the start(Stage primaryStage)
method.
o Create the Stage and Scene as the main container for the app.
2. Set Up the Layout:
o Use a GridPane to arrange components in a structured grid layout.
o Set appropriate padding, alignment, and spacing for a clean look.
3. Add Components to the Layout:
o Create labels for instructions (e.g., "Enter Bill Amount").
o Add a TextField for bill input.
o Create a ComboBox for selecting tip percentages (e.g., 10%, 15%, 20%).
o Add a Button labeled "Calculate Tip".
o Add a result Label to display the total amount after calculation.
4. Handle Button Click Events:
o Add an event handler to the "Calculate Tip" button.
o Retrieve the entered bill amount from the TextField.
o Get the selected tip percentage from the ComboBox.
o Calculate the tip and total amount.
o Display the result in the result Label.
5. Set the Scene and Show the Stage:
o Set the Scene with the GridPane as the root node to the primary Stage.
o Call the show() method to display the window.

Event Handling Example:

 TextField: Retrieve the value using getText().


 ComboBox: Get the selected item using getValue().
 Button: Attach an event handler to respond to the button click.
 Label: Update the text to display the result.

Example Workflow (without code):

1. The user enters a bill amount in the TextField.


2. The user selects a tip percentage from the ComboBox.
3. The user clicks the "Calculate Tip" button.
4. The event handler calculates the total amount (bill + tip) and updates the result Label.

GUI Interaction Logic:

 Input Validation: Ensure that the user enters a valid number in the TextField. You
can use try-catch to handle NumberFormatException if the input is invalid.
 Tip Calculation: The formula for calculating the total amount is:
 Displaying Result: Update the Label with the formatted result, including both the
original bill and the calculated tip.

This structure allows you to build a fully functional Tip Calculator app in JavaFX, utilizing
various components and learning how to manage user input and event handling.
Exercise – 9
a) Write a java program that connects to a database using JDBC

To connect to a database using JDBC in Java, you need the JDBC API and a corresponding
database driver (such as MySQL, PostgreSQL, etc.). Here is an example of how to connect to
a MySQL database using JDBC.

Steps:

1. Add JDBC Driver: You need to include the MySQL JDBC driver in your project. If
you're using Maven, you can include the following dependency in your [Link]:

Xml:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>

If not using Maven, you can manually download the MySQL Connector/J from the
MySQL website and add it to your classpath.

2. Java Program: Here's an example of how to connect to a MySQL database using


JDBC.

Example: Connect to MySQL Database


import [Link];
import [Link];
import [Link];

public class JDBCExample {

// Database URL, Username and Password


static final String DB_URL =
"jdbc:mysql://localhost:3306/your_database";
static final String USER = "root";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;

try {
// Step 1: Register the JDBC driver (Optional in newer versions)
[Link]("[Link]");

// Step 2: Open a connection


[Link]("Connecting to database...");
conn = [Link](DB_URL, USER, PASS);

[Link]("Connection successful!");

} catch (SQLException se) {


// Handle errors for JDBC
[Link]();
} catch (Exception e) {
// Handle errors for [Link]
[Link]();
} finally {
// Step 3: Close the connection (clean up)
try {
if (conn != null) [Link]();
} catch (SQLException se) {
[Link]();
}
}

[Link]("Goodbye!");
}
}

Key Points:

1. JDBC URL:
o jdbc:mysql://localhost:3306/your_database: The URL specifies the
type of database (mysql), the host (localhost), the port (3306), and the
database name (your_database).
2. Driver:
o [Link]: This is the MySQL JDBC driver.
3. Credentials:
o Replace USER and PASS with your actual database username and password.
4. Closing Resources:
o Always ensure the connection is closed after use to prevent resource leaks.

Make sure you replace the database URL, username, password, and driver based on the specific
database you are using.
b) Write a java program to connect to a database using JDBC and insert values into it.

Here's an example of how to connect to a MySQL database using JDBC and insert values into
a table.

Steps:

1. Database Setup: Make sure you have a MySQL table set up. For example, create a
table in your database:

Sql:
CREATE DATABASE testdb;

USE testdb;

CREATE TABLE employees (


id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
email VARCHAR(100)
);

2. Java Program: The program below connects to the testdb database and inserts values
into the employees table.

Example: Insert Values into Database


import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCInsertExample {

// Database URL, Username, and Password


static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
static final String USER = "root";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
PreparedStatement pstmt = null;

try {
// Step 1: Register JDBC driver (Optional in newer versions)
[Link]("[Link]");

// Step 2: Open a connection


[Link]("Connecting to database...");
conn = [Link](DB_URL, USER, PASS);

// Step 3: Create a SQL insert query


String sql = "INSERT INTO employees (first_name, last_name, age,
email) VALUES (?, ?, ?, ?)";
// Step 4: Create a PreparedStatement object
pstmt = [Link](sql);

// Step 5: Set the parameters


[Link](1, "John");
[Link](2, "Doe");
[Link](3, 30);
[Link](4, "[Link]@[Link]");

// Step 6: Execute the query


int rowsAffected = [Link]();

[Link]("Rows inserted: " + rowsAffected);

} catch (SQLException se) {


[Link]();
} catch (Exception e) {
[Link]();
} finally {
// Step 7: Clean up environment by closing connections
try {
if (pstmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException se) {
[Link]();
}
}

[Link]("Goodbye!");
}
}

Key Points:

1. SQL Query:
o The SQL query is:

sql
Copy code
INSERT INTO employees (first_name, last_name, age, email) VALUES
(?, ?, ?, ?)

o The ? placeholders will be filled with actual data using the PreparedStatement
object.
2. PreparedStatement:
o [Link](1, "John");: This sets the first parameter (first_name) to
"John".
o [Link](3, 30);: This sets the third parameter (age) to 30.
3. Execute Update:
o [Link]();: This executes the insert operation. It returns the
number of rows affected, which in this case should be 1 if successful.
4. Exception Handling:
o Handle any SQL or class loading errors appropriately.
Important Notes:

 Make sure to replace USER, PASS, and DB_URL with your actual database credentials.
 Always close your Connection and PreparedStatement objects to avoid potential
resource leaks.

This will insert a new employee record into the employees table.
c) Write a java program to connect to a database using JDBC and delete values from it.

Here’s an example of how to connect to a MySQL database using JDBC and delete values from
a table.

Steps:

1. Database Setup: Assume you have a MySQL table named employees with the
following structure:

sql:
CREATE DATABASE testdb;

USE testdb;

CREATE TABLE employees (


id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
email VARCHAR(100)
);

2. Java Program: The program below connects to the testdb database and deletes a
specific record from the employees table based on a condition (in this case, the id).

Example: Delete Values from Database


import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCDeleteExample {

// Database URL, Username, and Password


static final String DB_URL = "jdbc:mysql://localhost:3306/testdb";
static final String USER = "root";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
PreparedStatement pstmt = null;

try {
// Step 1: Register JDBC driver (Optional in newer versions)
[Link]("[Link]");

// Step 2: Open a connection


[Link]("Connecting to database...");
conn = [Link](DB_URL, USER, PASS);

// Step 3: Create SQL delete query


String sql = "DELETE FROM employees WHERE id = ?";

// Step 4: Create a PreparedStatement object


pstmt = [Link](sql);
// Step 5: Set the parameter (the ID of the employee to delete)
[Link](1, 1); // Assuming you want to delete the employee
with id = 1

// Step 6: Execute the delete operation


int rowsAffected = [Link]();

// Step 7: Check if the delete operation was successful


if (rowsAffected > 0) {
[Link]("Record deleted successfully.");
} else {
[Link]("No record found with the given ID.");
}

} catch (SQLException se) {


// Handle errors for JDBC
[Link]();
} catch (Exception e) {
// Handle errors for [Link]
[Link]();
} finally {
// Step 8: Clean up environment by closing connections
try {
if (pstmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException se) {
[Link]();
}
}

[Link]("Goodbye!");
}
}

Key Points:

1. SQL Query:
o The SQL query is:

sql
Copy code
DELETE FROM employees WHERE id = ?

o The ? is a placeholder that is set using the PreparedStatement object.


2. PreparedStatement:
o [Link](1, 1);: This sets the first parameter (the id of the employee to
delete) to 1. You can modify this to any other valid id.
3. Execute Update:
o [Link]();: This method executes the delete operation. It
returns the number of rows affected. If a row with the given ID is found and
deleted, the returned value will be greater than 0.
4. Exception Handling:
o Proper error handling ensures that SQL and class loading errors are caught and
dealt with accordingly.
5. Clean-up:
o The Connection and PreparedStatement objects are closed in the finally
block to avoid resource leaks.

Important Notes:

 Update USER, PASS, and DB_URL with your actual database credentials.
 The DELETE query only removes rows that match the condition (WHERE id = ?), so
make sure the condition is correct.

This will delete a record from the employees table where the id matches the given parameter
(in this case, id = 1).

You might also like