BVC COLLEGE OF ENGINEERING
(An Autonomous Institution)
Department of Computer Science and Engineering
LABORATORY MANUAL
OBJECT ORIENTED PROGRAMMING THROUGH JAVA
(Common for CSE, CSE (AI&ML), IT AND AIDS)
II Year - I Semester
VR23 REGUALTIONS
(Effective from 2023-2027 batch)
Name: ________________________________________
Roll No: _______________________________________
Branch: _______________________________________
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Section: _______________________________________
Course Outcomes (COs)
At the end of this course, the student will be able to:
CO1: Apply fundamental Java syntax, control structures, and array manipulations to solve basic
computational problems.
CO2: Implement the core principles of Object-Oriented Programming, including classes, objects,
methods, and constructors.
CO3: Design and develop applications using advanced OOP concepts such as inheritance,
polymorphism, abstract classes, and interfaces.
CO4: Develop robust and concurrent applications by implementing exception handling,
multithreading, and user-defined packages.
CO5: Build data-driven and graphical user interface (GUI) applications by integrating File I/O,
JDBC for database connectivity, and JavaFX.
Program Outcomes (POs) Addressed
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
CO-PO Mapping
Course Outcome PO1 PO2 PO3 PO5 PO12
CO1 ✓ ✓
CO2 ✓ ✓ ✓
CO3 ✓ ✓ ✓ ✓
CO4 ✓ ✓
CO5 ✓ ✓ ✓
MSN, BVCR Page 2
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
General Lab Instructions
General Lab Instructions
1. Students are expected to be punctual for the lab sessions and should be in formal dress code.
2. Students should come prepared for the experiment by thoroughly reading the relevant theory
and procedure in advance.
3. Maintain a neat and professional lab record book, documenting all experiments with
observations and results.
4. Follow the instructions given by the faculty carefully and perform the experiments diligently.
5. Ensure proper shutdown of all equipment after the completion of each lab session.
6. In case of any difficulty or need for assistance, students should promptly consult the faculty.
7. Strictly adhere to safety precautions while working in the lab.
8. Any damage to equipment due to negligence or mishandling will be the responsibility of the
student.
9. Regular attendance and active participation in lab sessions are mandatory.
10. Maintain discipline and a conducive learning environment in the laboratory.
MSN, BVCR Page 3
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
INDEX
[Link] Experiment Date Sign
1 Expt 1a: Displaying Default Values of Primitive Types
2 Expt 1b: Finding Roots of a Quadratic Equation
3 Expt 2a: Searching an Element using Binary Search
4 Expt 2b: Sorting an Array using Bubble Sort
5 Expt 2c: StringBuffer and StringBuilder Manipulation
6 Additional: Factorial and Palindrome Programs using Loops
7 Expt 3a: Implementing a Basic Class Mechanism (Box Class)
8 Expt 3b: Implementing Method Overloading
9 Expt 3c & 3d: Constructor Implementation & Overloading
10 Expt 4a: Implementing Single Inheritance
11 Expt 4b: Implementing Multilevel Inheritance
12 Expt 5a: Using the super Keyword
13 Expt 4c: Implementing Abstract Classes and Methods
14 Expt 5c: Implementing Runtime Polymorphism
15 Expt 5b: Implementing Interfaces for Multiple Inheritance
16 Additional: Creating and Manipulating an Array of Objects
17 Additional: Matrix Multiplication using 2D Arrays
18 Expt 6a: Basic Exception Handling with try-catch
19 Expt 6b: Using Multiple catch Clauses
20 Expt 6c: Causing and Handling Built-in Exceptions
21 Expt 6d: Creating and Using a User-Defined Exception
22 Expt 8a: Creating and Using User-Defined Packages
23 Additional: Copying a File using I/O Streams
24 Additional: Counting Words in a Text File
25 Expt 7a: Creating Threads by Extending Thread and
Implementing Runnable
26 Expt 7b: Using isAlive() and join() Thread Methods
27 Expt 7c: Illustrating Daemon Threads
28 Expt 7d: Solving the Producer-Consumer Problem
29 Expt 9a: Establishing a Database Connection using JDBC
30 Expt 9b: Inserting and Updating Data in a Database
31 Expt 8b: Building a Basic GUI with JavaFX and FXML
32 Expt 8c: Building an Interactive GUI Application (Tip Calculator)
33 Expt 9c: Deleting Data from a Database using JDBC
34 Mini-Project: Student Management System (CRUD Application)
MSN, BVCR Page 4
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Day to Day Evaluation
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
MSN, BVCR Page 5
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
MSN, BVCR Page 6
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
MSN, BVCR Page 7
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
MSN, BVCR Page 8
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
MSN, BVCR Page 9
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
Experiment : ______________________________________________________________________
Criteria Max Marks Marks Awarded Remarks
Code Correctness 5
Output Accuracy 3
Viva & Understanding 2
Total 10
Date: _______________________
Faculty Signature: _______________________
MSN, BVCR Page 10
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Week 1: Basic Java Syntax and I/O
Experiment 1.a: Displaying Default Values
Objective: To understand and observe the default values that Java assigns to uninitialized
primitive member variables.
Procedure:
1. Logic: In Java, instance variables of primitive types are automatically assigned a
default value if they are not explicitly initialized. This prevents uninitialized data
errors.
2. Create a Java class named DefaultValuesDemo.
3. Inside the class, declare member variables for all 8 primitive types: byte b; short s;
int i; long l; float f; double d; char c; boolean bool;.
4. In the main method, create an object of
the DefaultValuesDemo class: DefaultValuesDemo demo = new
DefaultValuesDemo();.
5. Print the value of each member variable using the created object to observe its
default value.
Example Code Snippet:
Class DefaultValuesDemo {
byte b;
short s;
int i;
long l;
float f;
double d;
char c;
boolean bool;
}
public class Main {
public static void main(String[] args) {
DefaultValuesDemo demo = new DefaultValuesDemo();
[Link]("Default value of byte: " + demo.b);
[Link]("Default value of short: " + demo.s);
[Link]("Default value of int: " + demo.i);
[Link]("Default value of long: " + demo.l);
[Link]("Default value of float: " + demo.f);
[Link]("Default value of double: " + demo.d);
MSN, BVCR Page 11
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]("Default value of char (as int): " + (int) demo.c); // char default is
'\u0000'
[Link]("Default value of boolean: " + [Link]);
}
}
Expected Output / Sample Test Cases:
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 (as int): 0
Default value of boolean: false
Observations:
Viva Questions:
1. What is the default value of a char in Java?
oAnswer: The default value is \u0000, which is the null character.
2. Do local variables get default values in Java?
o Answer: No. Local variables (variables declared inside a method) must be
explicitly initialized before they are used. The compiler will throw an error if
you try to use an uninitialized local variable.
3. What is the default value for any object reference variable?
o Answer: The default value for any object reference (e.g., String s;) is null.
MSN, BVCR Page 12
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Experiment 1.b: Quadratic Equation Roots
Objective: To write a program that takes user input, performs calculations based on
conditional logic, and displays the results.
Procedure:
1. Logic: The nature of the roots of a quadratic equation ax²+bx+c=0 depends on its
discriminant, D = b² - 4ac.
o If D > 0, roots are real and distinct.
o If D = 0, roots are real and equal.
o If D < 0, roots are complex/imaginary.
2. Import the [Link] class. In the main method, create a Scanner object.
3. Prompt the user to enter the coefficients a, b, and c, and read them
as double values.
4. Calculate the discriminant.
5. Use an if-else if-else structure to check the value of D and print the nature of the
roots.
6. If the roots are real (D >= 0), calculate them using the formula (-b ± √D) / 2a and
display the values.
Example Code Snippet:
import [Link];
public class QuadraticRoots {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter coefficients a, b, and c:");
double a = [Link]();
double b = [Link]();
double c = [Link]();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + [Link](discriminant)) / (2 * a);
double root2 = (-b - [Link](discriminant)) / (2 * a);
[Link]("Roots are real and distinct.");
[Link]("Root 1 = %.2f and Root 2 = %.2f\n", root1, root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
[Link]("Roots are real and equal.");
[Link]("Root = %.2f\n", root);
MSN, BVCR Page 13
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
} else {
[Link]("Roots are complex and imaginary.");
}
[Link]();
}
}
Expected Output / Sample Test Cases:
Input (Real, Distinct): a=1, b=-5, c=6 -> Output: Roots are real and distinct. Root 1 =
3.00 and Root 2 = 2.00
Input (Real, Equal): a=1, b=4, c=4 -> Output: Roots are real and equal. Root = -2.00
Input (Complex): a=1, b=1, c=1 -> Output: Roots are complex and imaginary.
Observations:
Viva Questions:
1. What class is used for taking input from the console in Java?
o Answer: The [Link] class is commonly used.
2. What does the [Link]() method do?
o Answer: It returns the correctly rounded positive square root of
a double value.
3. Why is it important to close the Scanner object ([Link]())?
MSN, BVCR Page 14
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Answer: It is good practice to close the Scanner object to release the
underlying system resources (like the input stream) that it is holding. This
prevents resource leaks.
Week 2: Searching, Sorting & String Intro
Experiment 2.a: Binary Search
Objective: To implement the binary search algorithm to efficiently find an element in a
sorted array.
Procedure:
1. Logic: Binary search works by repeatedly dividing the search interval in half. If the
value of the search key is less than the item in the middle of the interval, narrow the
interval to the lower half. Otherwise, narrow it to the upper half.
2. Create a class named BinarySearchDemo.
3. Define a public static int binarySearch(int[] arr, int target) method. Initialize low =
0 and high = [Link] - 1.
4. Implement a while loop that continues as long as low <= high.
5. Inside the loop, calculate the middle index: int mid = low + (high - low) / 2; to avoid
potential overflow.
6. Compare arr[mid] with target. If they are equal, return mid.
7. If arr[mid] is less than target, discard the lower half by setting low = mid + 1.
8. Otherwise, discard the upper half by setting high = mid - 1.
9. If the loop terminates, the element is not present. Return -1.
10. In the main method, create a sorted integer array. Call the binarySearch method
with different test cases and print the results to verify correctness.
Example Code Snippet:
public class BinarySearchDemo {
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = [Link] - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // Element found
}
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
MSN, BVCR Page 15
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] sortedArray = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
// Test Cases
[Link]("Searching for 23: " + binarySearch(sortedArray, 23));
[Link]("Searching for 2: " + binarySearch(sortedArray, 2));
[Link]("Searching for 91: " + binarySearch(sortedArray, 91));
[Link]("Searching for 50: " + binarySearch(sortedArray, 50));
}
}
Expected Output / Sample Test Cases:
Searching for 23: 5
Searching for 2: 0
Searching for 91: 9
Searching for 50: -1
Observations:
Viva Questions:
1. What is the primary prerequisite for using binary search?
o Answer: The array or list must be sorted.
2. What is the time complexity of binary search? Why is it efficient?
o Answer: The time complexity is O(log n). It is efficient because it eliminates
half of the remaining elements from consideration with each comparison,
significantly reducing the search space.
MSN, BVCR Page 16
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
3. Why is mid = low + (high - low) / 2 preferred over mid = (low + high) / 2?
o Answer: The first form prevents a potential integer overflow that can occur
if low + high exceeds the maximum value of the int data type.
Experiment 2.b: Bubble Sort
Objective: To implement the bubble sort algorithm to sort an array of integers in ascending
order.
Procedure:
1. Logic: Bubble sort repeatedly steps through the list, compares adjacent elements,
and swaps them if they are in the wrong order. The pass through the list is repeated
until the list is sorted. The largest elements "bubble" up to the end of the array.
2. Create a class BubbleSortDemo.
3. In the main method, define an unsorted integer array. Print the array in its initial
state.
4. Implement two nested for loops. The outer loop (int i = 0; i < n - 1; i++) controls the
number of passes.
5. The inner loop (int j = 0; j < n - i - 1; j++) compares adjacent elements.
6. Inside the inner loop, if arr[j] is greater than arr[j + 1], swap them using a temporary
variable.
7. After the loops complete, print the now-sorted array.
Example Code Snippet:
import [Link];
public class BubbleSortDemo {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
[Link]("Array before sorting: " + [Link](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 arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
MSN, BVCR Page 17
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]("Array after sorting: " + [Link](arr));
}
}
Expected Output / Sample Test Cases:
Array before sorting: [64, 34, 25, 12, 22, 11, 90]
Array after sorting: [11, 12, 22, 25, 34, 64, 90]
Test with an already sorted array: [10, 20, 30] should remain [10, 20, 30].
Test with a reverse-sorted array: [5, 4, 3, 2, 1] should become [1, 2, 3, 4, 5].
Observations:
Viva Questions:
1. What is the time complexity of bubble sort in the worst and best cases?
o Answer: In the worst case (reverse-sorted array) and average case, the time
complexity is O(n²). In the best case (already sorted array), it is O(n) if an
optimization is added to stop early if no swaps occur in a pass.
2. Is bubble sort a stable sorting algorithm?
o Answer: Yes, it is stable. This means that if two elements have equal keys,
their relative order is preserved in the sorted output.
3. How can you optimize bubble sort?
MSN, BVCR Page 18
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Answer: By adding a flag that checks if any swaps were made during a pass. If
a full pass is completed with no swaps, the array is already sorted, and the
algorithm can terminate early.
Week 3: String Manipulation and Loop Mastery
Experiment 3.a: StringBuffer Manipulation
Objective: To demonstrate the mutability and methods of the StringBuffer class.
Procedure:
1. Logic: Unlike the immutable String class, StringBuffer (and StringBuilder) objects can
be modified after creation. This is efficient for programs that perform many string
modifications.
2. Create a class StringBufferDemo.
3. In the main method, create a StringBuffer object: StringBuffer sb = new
StringBuffer("Hello");.
4. Demonstrate appending: use [Link](" World"); and print the result.
5. Demonstrate insertion: use [Link](5, " Java"); and print the result.
6. Demonstrate deletion: use [Link](5, 10); to remove " Java" and print the result.
7. Demonstrate reversal: use [Link](); and print the final result.
Example Code Snippet:
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
[Link]("1. Original: " + sb);
[Link](" World");
[Link]("2. After append: " + sb);
[Link](5, " Java");
[Link]("3. After insert: " + sb);
[Link](5, 10); // Deletes " Java"
[Link]("4. After delete: " + sb);
[Link]();
[Link]("5. After reverse: " + sb);
}
}
MSN, BVCR Page 19
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Expected Output / Sample Test Cases:
1. Original: Hello
2. After append: Hello World
3. After insert: Hello Java World
4. After delete: HelloWorld
5. After reverse: dlroWolleH
Observations:
Viva Questions:
1. What is the main difference between String and StringBuffer?
o Answer: String objects are immutable (cannot be changed after
creation). StringBuffer objects are mutable (can be modified).
2. What is the difference between StringBuffer and StringBuilder?
o Answer: StringBuffer is thread-safe (synchronized), meaning its methods can
be safely used by multiple threads. StringBuilder is not thread-safe (non-
synchronized), but it is faster. StringBuilder should be used in single-threaded
environments.
3. Why is using + to concatenate strings in a loop inefficient?
MSN, BVCR Page 20
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Answer: Because String is immutable, each concatenation creates a
new String object in memory. In a loop, this leads to the creation of many
intermediate objects, which is inefficient and puts pressure on the garbage
collector. StringBuilder or StringBuffer should be used instead.
Experiment 3.b: Factorial and Palindrome
Objective: To use loops to solve common computational problems like calculating factorial
and checking for palindromes.
Procedure:
1. Logic (Factorial): The factorial of a non-negative integer 'n' is the product of all
positive integers less than or equal to 'n'.
2. Logic (Palindrome): A palindrome is a sequence that reads the same backward as
forward. The logic involves reversing the input sequence and comparing it to the
original.
3. Create a class LoopMastery. In the main method, create a Scanner object for input.
4. Factorial Part:
o Prompt the user for a number.
o Initialize long factorial = 1;.
o Use a for loop (int i = 1; i <= num; ++i) and update the factorial in each
iteration: factorial *= i;.
o Print the result.
5. Palindrome Part:
o Prompt the user for a string.
o Use StringBuilder for efficient reversal: String reversed = new
StringBuilder(original).reverse().toString();.
oCompare the original and reversed strings using .equalsIgnoreCase() to
handle case differences and print the result.
Example Code Snippet:
import [Link];
public class LoopMastery {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// --- Factorial ---
[Link]("Enter a number for factorial: ");
int num = [Link]();
long factorial = 1;
if (num >= 0) {
MSN, BVCR Page 21
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
[Link]("Factorial of %d = %d\n\n", num, factorial);
} else {
[Link]("Factorial is not defined for negative numbers.\n");
}
// --- Palindrome ---
[Link]("Enter a string for palindrome check: ");
String original = [Link]();
String reversed = new StringBuilder(original).reverse().toString();
if ([Link](reversed)) {
[Link](original + " is a palindrome.");
} else {
[Link](original + " is not a palindrome.");
}
[Link]();
}
}
Expected Output / Sample Test Cases:
Factorial Input: 5, Output: Factorial of 5 = 120
Factorial Input: 0, Output: Factorial of 0 = 1
Palindrome Input: "Racecar", Output: Racecar is a palindrome.
Palindrome Input: "hello", Output: hello is not a palindrome.
Observations:
Viva Questions:
1. What is the factorial of 0?
o Answer: By definition, the factorial of 0 is 1.
2. Why was long used for the factorial variable instead of int?
MSN, BVCR Page 22
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Answer: Factorial values grow very rapidly. The long data type has a much
larger range than int, allowing us to calculate factorials of larger numbers
before an overflow occurs (e.g., 20! fits in long but not int).
3. How would you check if a number is a palindrome without converting it to a string?
o Answer: You can use a loop. In each iteration, extract the last digit of the
number using the modulo operator (% 10), add it to
a reversedNumber variable, and then remove the last digit from the original
number by integer division (/ 10). Repeat until the original number becomes
0, then compare it with the reversedNumber.
Week 4: Classes, Objects, Methods, and Constructors
Experiment 4.a: Class Mechanism (Box Volume)
Objective: To implement a basic class with properties and methods, and create objects
(instances) of that class.
Procedure:
1. Logic: A class acts as a blueprint for creating objects. It encapsulates data
(properties) and behavior (methods) into a single unit.
2. Create a class named Box.
3. Inside Box, declare three double member variables: width, height, and depth.
4. Define a method void calculateVolume() that prints the volume calculated as width
* height * depth.
5. In a separate class BoxDemo, create a main method.
6. Instantiate two Box objects: Box box1 = new Box(); and Box box2 = new Box();.
7. Assign distinct values to the width, height, and depth properties of box1 and box2.
8. Call the calculateVolume() method on both box1 and box2 to see that each object
maintains its own state.
Example Code Snippet:
class Box {
double width;
double height;
double depth;
void calculateVolume() {
[Link]("Volume is: " + (width * height * depth));
}
}
MSN, BVCR Page 23
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
public class BoxDemo {
public static void main(String[] args) {
// Test Case 1
Box box1 = new Box();
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link]("Volume of box1: ");
[Link]();
// Test Case 2
Box box2 = new Box();
[Link] = 3.5;
[Link] = 6.0;
[Link] = 9.2;
[Link]("Volume of box2: ");
[Link]();
}
}
Expected Output / Sample Test Cases:
Volume of box1: Volume is: 3000.0
Volume of box2: Volume is: 193.2
Observations:
Viva Questions:
1. What is the difference between a class and an object?
MSN, BVCR Page 24
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Answer: A class is a blueprint or template from which objects are created. An
o
object is an instance of a class, representing a real-world entity with state
and behavior.
2. What are instance variables?
o Answer: Instance variables (or member variables) are variables declared
within a class but outside any method. Each object of the class has its own
separate copy of these variables.
3. What does the new keyword do?
o Answer: The new keyword is used to dynamically allocate memory for a new
object and return a reference to that memory.
Experiment 4.b: Method Overloading
Objective: To implement method overloading, allowing a class to have multiple methods
with the same name but different parameters.
Procedure:
1. Logic: Method overloading is a form of compile-time polymorphism. The compiler
decides which method to call based on the number, type, and order of the
arguments passed during the method call.
2. Create a class MathOperations.
3. Define a method int add(int a, int b) that returns the sum of two integers.
4. Define another method int add(int a, int b, int c) that returns the sum of three
integers.
5. Define a third method double add(double a, double b) that returns the sum of two
doubles.
6. In a main method, create an object of MathOperations.
7. Call the add method with different sets of arguments (two integers, three integers,
two doubles) and print the results to demonstrate that Java calls the correct
overloaded method each time.
Example Code Snippet:
class MathOperations {
// Overloaded method 1
int add(int a, int b) {
return a + b;
}
// Overloaded method 2
int add(int a, int b, int c) {
return a + b + c;
}
MSN, BVCR Page 25
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
// Overloaded method 3
double add(double a, double b) {
return a + b;
}
}
public class OverloadingDemo {
public static void main(String[] args) {
MathOperations math = new MathOperations();
// Test Cases
[Link]("Sum of two integers (5, 10): " + [Link](5, 10));
[Link]("Sum of three integers (5, 10, 15): " + [Link](5, 10, 15));
[Link]("Sum of two doubles (5.5, 10.5): " + [Link](5.5, 10.5));
}
}
Expected Output / Sample Test Cases:
Sum of two integers (5, 10): 15
Sum of three integers (5, 10, 15): 30
Sum of two doubles (5.5, 10.5): 16.0
Observations:
Viva Questions:
1. Can we overload methods by just changing the return type?
MSN, BVCR Page 26
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
oAnswer: No. Method overloading in Java is not possible by changing only the
return type of the method. The method signature (name and parameter list)
must be different.
2. Is method overloading an example of compile-time or run-time polymorphism?
o Answer: It is an example of compile-time polymorphism (or static binding),
because the compiler determines which method to execute at compile time
based on the arguments provided.
3. Can we overload the main() method?
o Answer: Yes, the main() method can be overloaded just like any other
method. However, the JVM will only call the main() method with the
signature public static void main(String[] args).
Experiment 4.c & 4.d: Constructor Implementation & Overloading
Objective: To implement and overload constructors to initialize objects in different ways
upon creation.
Procedure:
1. Logic: A constructor is a special method used to initialize an object. It is called
automatically when an object is created using the new keyword. Overloading
constructors provides multiple ways to create and initialize an object.
2. Create a class Student.
3. Declare instance variables String name and int rollNo.
4. Default Constructor (Overloading Part): Create a no-argument constructor public
Student() that sets default values (e.g., name to "Unknown", rollNo to 0).
5. Parameterized Constructor (Implementation Part): Create a parameterized
constructor public Student(String name, int rollNo) that uses the this keyword to
initialize the instance variables with the provided arguments ([Link] = name;).
6. Second Parameterized Constructor (Overloading Part): Create another
constructor public Student(String name) that initializes only the name and sets a
default roll number.
7. Create a display() method to print the student's details.
8. In a main method, create Student objects using all three constructors and call
the display() method for each to verify the initial state.
Example Code Snippet:
class Student {
String name;
int rollNo;
// 1. Default constructor
Student() {
[Link] = "Unknown";
[Link] = 0;
MSN, BVCR Page 27
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
}
// 2. Parameterized constructor for both properties
Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
// 3. Overloaded constructor for just name
Student(String name) {
[Link] = name;
[Link] = -1; // Default for this constructor
}
void display() {
[Link]("Name: " + name + ", Roll No: " + rollNo);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
// Test Cases
[Link]("Student 1 (Default): ");
Student s1 = new Student();
[Link]();
[Link]("Student 2 (Name and Roll): ");
Student s2 = new Student("Alice", 101);
[Link]();
[Link]("Student 3 (Name only): ");
Student s3 = new Student("Bob");
[Link]();
}
}
Expected Output / Sample Test Cases:
Student 1 (Default): Name: Unknown, Roll No: 0
Student 2 (Name and Roll): Name: Alice, Roll No: 101
Student 3 (Name only): Name: Bob, Roll No: -1
Observations:
MSN, BVCR Page 28
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What are the rules for creating a constructor?
o Answer: A constructor must have the same name as the class it is in, and it
cannot have an explicit return type (not even void).
2. What is the purpose of the this keyword in a constructor?
o Answer: It is used to refer to the current object. It is primarily used to
differentiate between instance variables and parameters when they have the
same name.
3. What is constructor chaining?
o Answer: Constructor chaining is the process of calling one constructor from
another within the same class. This is done using this(). It must be the first
statement in the constructor.
Week 5: Inheritance and the super Keyword
Experiment 5.a & 5.b: Single and Multilevel Inheritance
Objective: To implement single and multilevel inheritance to demonstrate code reusability
and hierarchical relationships.
Procedure:
1. Logic: Inheritance allows a new class (subclass) to acquire the properties and
methods of an existing class (superclass). In multilevel inheritance, a class is derived
from another derived class.
2. Single Inheritance:
o Create a base class Animal with a method void eat() that prints "This animal
eats food."
o Create a derived class Dog that extends Animal. Add a method void
bark() that prints "Dog is barking."
3. Multilevel Inheritance:
o Create a class Puppy that extends Dog. Add a method void weep() that
prints "Puppy is weeping."
4. In a main method:
o Create a Dog object and call both eat() and bark() methods to demonstrate
single inheritance.
o Create a Puppy object and call eat(), bark(), and weep() methods to
demonstrate multilevel inheritance.
Example Code Snippet:
// Base class
class Animal {
void eat() {
[Link]("This animal eats food.");
}
MSN, BVCR Page 29
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
}
// Derived class (Single Inheritance)
class Dog extends Animal {
void bark() {
[Link]("Dog is barking.");
}
}
// Derived from a derived class (Multilevel Inheritance)
class Puppy extends Dog {
void weep() {
[Link]("Puppy is weeping.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
// Test Case 1: Single Inheritance
[Link]("--- Single Inheritance ---");
Dog myDog = new Dog();
[Link]();
[Link]();
// Test Case 2: Multilevel Inheritance
[Link]("\n--- Multilevel Inheritance ---");
Puppy myPuppy = new Puppy();
[Link]();
[Link]();
[Link]();
}
}
Expected Output / Sample Test Cases:
--- Single Inheritance ---
This animal eats food.
Dog is barking.
--- Multilevel Inheritance ---
This animal eats food.
Dog is barking.
Puppy is weeping.
MSN, BVCR Page 30
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Observations:
Viva Questions:
1. What is an "is-a" relationship in Java?
o Answer: Inheritance represents an "is-a" relationship. For example, a Dog "is-
a" Animal.
2. Why does Java not support multiple inheritance (extending more than one class)?
o Answer: To avoid the "Diamond Problem," which creates ambiguity when a
class inherits from two superclasses that have a method with the same name.
Java avoids this complexity by allowing a class to extend only one other class.
3. What members of a superclass are not inherited by the subclass?
o Answer: private members and constructors of the superclass are not
inherited by the subclass. However, the superclass constructor is always
called from the subclass constructor (either explicitly using super() or
implicitly by the compiler).
Experiment 5.c: "super" Keyword Example
Objective: To use the super keyword to access members (methods and constructors) of the
immediate superclass.
Procedure:
1. Logic: The super keyword is a reference variable that is used to refer to the
immediate parent class object. It can be used to call the parent class's methods or
constructors.
2. Create a class Person with a String name and a constructor to initialize it. Also,
create a method void display() that prints the person's name.
3. Create a class Employee that extends Person. Add a double salary property.
4. In the Employee constructor, use super(name); as the first statement to call
the Person constructor and initialize the name. Then, initialize the salary.
MSN, BVCR Page 31
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
5. In the Employee class, override the display() method. Inside this method, first call
the parent's display method using [Link]();, then print the employee's salary.
6. In a main method, create an Employee object and call its display() method to
demonstrate both uses of super.
Example Code Snippet:
class Person {
String name;
Person(String name) {
[Link] = name;
}
void display() {
[Link]("Name: " + [Link]);
}
}
class Employee extends Person {
double salary;
Employee(String name, double salary) {
// 1. Use super() to call the parent constructor
super(name);
[Link] = salary;
}
@Override
void display() {
// 2. Use super to call the parent method
[Link]();
[Link]("Salary: " + [Link]);
}
}
public class SuperDemo {
public static void main(String[] args) {
// Test Case
Employee emp1 = new Employee("John Doe", 75000.0);
[Link]("Employee Details:");
MSN, BVCR Page 32
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]();
}
}
Expected Output / Sample Test Cases:
Employee Details:
Name: John Doe
Salary: 75000.0
Observations:
Viva Questions:
1. What are the two primary uses of the super keyword?
o Answer: 1. To call the constructor of the immediate superclass (super()). 2.
To access a method or variable of the immediate superclass
([Link]()).
2. Can super() be used anywhere in a constructor?
o Answer: No, the call to super() must be the very first statement in the
subclass constructor.
3. What is the difference between this and super?
o Answer: this refers to the current object instance. super refers to the
immediate parent class object instance.
Week 6: Polymorphism, Abstract Classes, and
Interfaces
Experiment 6.a: Abstract Classes
Objective: To use an abstract class to define a common template for a group of subclasses,
forcing them to implement specific behavior.
Procedure:
1. Logic: An abstract class cannot be instantiated. It serves as a base for subclasses,
defining abstract methods (with no body) that must be implemented by any
concrete (non-abstract) subclass.
2. Create an abstract class Shape.
3. Inside Shape, define an abstract method double calculateArea();.
MSN, BVCR Page 33
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
4. Also, define a concrete (regular) method void display() { [Link]("This is a
shape."); }.
5. Create a class Circle that extends Shape. It must provide an implementation
for calculateArea(). Give it a radius property and a constructor. The area is [Link]
* radius * radius.
6. Create a class Rectangle that extends Shape. It must also
implement calculateArea(). Give it width and height properties and a constructor.
The area is width * height.
7. In a main method, create objects of Circle and Rectangle. Call
their display() and calculateArea() methods. Attempting to create an object
of Shape (new Shape()) will result in a compile-time error.
Example Code Snippet:
abstract class Shape {
// Abstract method (does not have a body)
abstract double calculateArea();
// Regular method
void display() {
[Link]("This is a shape.");
}
}
class Circle extends Shape {
double radius;
Circle(double r) { [Link] = r; }
@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
class Rectangle extends Shape {
double width, height;
Rectangle(double w, double h) { [Link] = w; [Link] = h; }
@Override
double calculateArea() {
MSN, BVCR Page 34
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
return width * height;
}
}
public class AbstractDemo {
public static void main(String[] args) {
// Test Cases
Circle c = new Circle(5.0);
Rectangle r = new Rectangle(4.0, 6.0);
[Link]();
[Link]("Area of Circle: %.2f\n", [Link]());
[Link]();
[Link]("Area of Rectangle: %.2f\n", [Link]());
}
}
Expected Output / Sample Test Cases:
This is a shape.
Area of Circle: 78.54
This is a shape.
Area of Rectangle: 24.00
Observations:
MSN, BVCR Page 35
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. Can an abstract class have a constructor?
o Answer: Yes. While you cannot create an object of an abstract class directly,
its constructor is called from the subclass constructor (using super()) to
initialize the members of the abstract class.
2. What is the difference between an abstract class and an interface?
o Answer: An abstract class can have both abstract and non-abstract (concrete)
methods, as well as instance variables. An interface (before Java 8) could only
have abstract methods and public static final constants. An abstract class is
used for an "is-a" relationship, while an interface is used to define a "can-do"
capability.
3. If a class extends an abstract class but does not implement all its abstract methods,
what must be done?
o Answer: The subclass must also be declared as abstract.
Experiment 6.b: Runtime Polymorphism
Objective: To implement runtime polymorphism (dynamic method dispatch) by using a
superclass reference to refer to a subclass object.
Procedure:
1. Logic: Runtime polymorphism allows the method to be called to be determined at
runtime, based on the type of the object, not the type of the reference variable. This
is achieved through method overriding and upcasting.
2. Reuse the Shape, Circle, and Rectangle classes from the previous experiment.
3. In a main method, create a reference variable of the superclass type: Shape
shapeRef;.
4. Assign a subclass object to this reference: shapeRef = new Circle(7.0);.
5. Call the calculateArea() method using the reference: [Link](). The
JVM will dynamically call the Circle's version of the method.
6. Reassign a different subclass object to the same reference: shapeRef = new
Rectangle(5.0, 10.0);.
7. Call calculateArea() again. This time, the Rectangle's version will be executed.
Example Code Snippet:
// Reuse Shape, Circle, Rectangle classes from Experiment 6.a
public class PolymorphismDemo {
public static void main(String[] args) {
Shape shapeRef; // A reference of type Shape
// Test Case 1: Pointing to a Circle object
shapeRef = new Circle(7.0);
MSN, BVCR Page 36
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]("Using Shape reference for Circle object. ");
[Link]("Area: %.2f\n", [Link]());
// Test Case 2: Pointing to a Rectangle object
shapeRef = new Rectangle(5.0, 10.0);
[Link]("Using Shape reference for Rectangle object. ");
[Link]("Area: %.2f\n", [Link]());
}
}
Expected Output / Sample Test Cases:
Using Shape reference for Circle object. Area: 153.94
Using Shape reference for Rectangle object. Area: 50.00
Observations:
Viva Questions:
1. What is upcasting?
o Answer: Upcasting is the process of casting a subclass type to a superclass
type. For example, Shape s = new Circle();. This is done implicitly and is
always safe.
2. How is method overriding essential for runtime polymorphism?
o Answer: Method overriding provides the different implementations of the
same method in various subclasses. Runtime polymorphism uses this
mechanism to decide which specific implementation to execute at runtime
based on the actual object being referred to.
3. Can we override a static method?
o Answer: No. static methods are bound at compile time (a concept called
method hiding), not runtime. Therefore, they cannot be overridden to
achieve runtime polymorphism.
Experiment 6.c: Interfaces
Objective: To use interfaces to define a contract for classes and achieve a form of multiple
inheritance.
Procedure:
1. Logic: An interface is a completely abstract type that is used to group related
methods with empty bodies. A class can implement multiple interfaces, inheriting
their abstract methods.
2. Create an interface Player with two abstract methods: void play(); and void stop();.
MSN, BVCR Page 37
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
3. Create another interface Recorder with a method void record();.
4. Create a class Walkman that implements Player, Recorder.
5. The Walkman class must provide concrete implementations for all methods from
both interfaces (play, stop, record). Each implementation should just be a print
statement.
6. In a main method, create a Walkman object and call all three methods to
demonstrate that the class has successfully implemented the behaviors from both
interfaces.
Example Code Snippet:
interface Player {
void play();
void stop();
}
interface Recorder {
void record();
}
// This class implements two interfaces
class Walkman implements Player, Recorder {
@Override
public void play() {
[Link]("Playing music...");
}
@Override
public void stop() {
[Link]("Music stopped.");
}
@Override
public void record() {
[Link]("Recording audio...");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
// Test Case
Walkman myDevice = new Walkman();
[Link]();
[Link]();
[Link]();
MSN, BVCR Page 38
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
}
}
Expected Output / Sample Test Cases:
Playing music...
Recording audio...
Music stopped.
Observations:
Viva Questions:
1. What is 100% abstraction?
o Answer: An interface provides 100% abstraction (before Java 8) because it
can only contain abstract methods. It specifies what a class can do but
not how it does it.
2. What are the default modifiers for methods and variables in an interface?
o Answer: All methods in an interface are implicitly public and abstract. All
variables are implicitly public, static, and final.
3. Since Java 8, interfaces can have default and static methods. What is their
purpose?
o Answer: default methods allow adding new methods to interfaces without
breaking existing implementing classes. static methods are utility methods
that are related to the interface but are not tied to an object instance.
Week 7: Arrays of Objects & Multi-dimensional Arrays
Experiment 7.a: Array of Objects
Objective: To create and manipulate an array that holds object references, demonstrating
how to manage a collection of custom objects.
Procedure:
1. Logic: An array can hold references to objects just as it can hold primitive types. Each
element of the array acts as a reference variable pointing to an object in memory.
MSN, BVCR Page 39
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
2. Create a simple Student class with properties like String name and int rollNo.
Include a constructor and a display() method.
3. In a main method, declare an array of Student objects: Student[] studentArray =
new Student[3];. Note that this only creates the array, not the Student objects
themselves.
4. Use a for loop to iterate through the array. Inside the loop, you must instantiate
each Student object individually: studentArray[i] = new Student("Student " + (i+1),
101 + i);.
5. After populating the array, use another for-each loop to iterate through
the studentArray and call the display() method for each student object to print their
details.
Example Code Snippet:
class Student {
String name;
int rollNo;
Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}
void display() {
[Link]("Roll No: " + [Link] + ", Name: " + [Link]);
}
}
public class ArrayOfObjectsDemo {
public static void main(String[] args) {
// 1. Declare and create the array of references
Student[] studentArray = new Student[3];
// 2. Instantiate each object in the array
// Test Case data
studentArray[0] = new Student("Alice", 101);
studentArray[1] = new Student("Bob", 102);
studentArray[2] = new Student("Charlie", 103);
// 3. Display the details of all students
[Link]("Details of all students:");
for (Student s : studentArray) {
MSN, BVCR Page 40
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]();
}
}
}
Expected Output / Sample Test Cases:
Details of all students:
Roll No: 101, Name: Alice
Roll No: 102, Name: Bob
Roll No: 103, Name: Charlie
Observations:
Viva Questions:
1. What is stored in an array of objects? The objects themselves or references?
o Answer: The array stores references to the objects. The actual objects reside
in the heap memory.
2. What happens if you declare an array of objects Student[] s = new Student[5]; but
don't instantiate the individual objects?
o Answer: The array will be created with 5 elements, but each element will
have a default value of null. If you try to call a method on any element
(e.g., s[0].display();), it will result in a NullPointerException.
3. How can you sort an array of custom objects?
o Answer: You need to implement the Comparable interface in your custom
class and override the compareTo() method to define the natural sorting
order. Alternatively, you can create a separate Comparator class. Then, you
can use [Link]() to sort the array.
Experiment 7.b: Matrix Multiplication
Objective: To use two-dimensional arrays to perform the multiplication of two matrices.
Procedure:
1. Logic: To multiply two matrices, the number of columns in the first matrix must
equal the number of rows in the second. The element at position (i, j) in the result
MSN, BVCR Page 41
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
matrix is the dot product of the i-th row of the first matrix and the j-th column of
the second matrix.
2. In a main method, define two 2D integer arrays (matrices), matrixA and matrixB.
3. Define a third 2D array, resultMatrix, of the appropriate size to store the result.
4. Use three nested for loops to perform the multiplication:
o The outer loop iterates through the rows of matrixA (i).
o The middle loop iterates through the columns of matrixB (j).
o The inner loop iterates through the columns of matrixA (or rows of matrixB)
(k).
5. Inside the inner loop, calculate the sum of products: resultMatrix[i][j] +=
matrixA[i][k] * matrixB[k][j];.
6. After calculation, use another set of nested loops to print the resultMatrix in a
formatted way.
Example Code Snippet:
import [Link];
public class MatrixMultiplicationDemo {
public static void main(String[] args) {
// Test Case
int[][] matrixA = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] matrixB = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
int rowsA = [Link];
int colsA = matrixA[0].length;
int colsB = matrixB[0].length;
int[][] resultMatrix = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
MSN, BVCR Page 42
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]("Result of Matrix Multiplication:");
for (int[] row : resultMatrix) {
[Link]([Link](row));
}
}
}
Expected Output / Sample Test Cases:
Result of Matrix Multiplication:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
Observations:
Viva Questions:
1. How is a 2D array stored in memory in Java?
o Answer: A 2D array in Java is actually an array of arrays. The main array holds
references to other arrays, which in turn hold the data. This allows for
"jagged arrays" where each row can have a different number of columns.
2. What is the condition for matrix multiplication to be possible?
o Answer: The number of columns in the first matrix must be equal to the
number of rows in the second matrix.
3. How do you find the number of rows and columns in a 2D array int[][] arr?
o Answer: The number of rows is [Link]. The number of columns in the
first row is arr[0].length.
Week 8: Exception Handling
Experiment 8.a: Exception Handling Mechanism
Objective: To use the try-catch block to gracefully handle runtime exceptions and prevent
program termination.
Procedure:
MSN, BVCR Page 43
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
1. Logic: The try block encloses code that might throw an exception. If an exception
occurs within the try block, the program flow immediately jumps to the
corresponding catch block, skipping the rest of the try block.
2. Create a class BasicExceptionDemo.
3. In the main method, define two integers, a = 10 and b = 0.
4. Place the division operation int result = a / b; inside a try block.
5. Immediately after the try block, add a catch block that catches ArithmeticException.
6. Inside the catch block, print a user-friendly error message, such as "Error: Cannot
divide by zero."
7. Add a final print statement after the try-catch structure to demonstrate that the
program continues to execute instead of crashing.
Example Code Snippet:
public class BasicExceptionDemo {
public static void main(String[] args) {
try {
// This code will cause an ArithmeticException
int a = 10;
int b = 0;
[Link]("Attempting to divide...");
int result = a / b;
[Link]("Result: " + result); // This line will not be reached
} catch (ArithmeticException e) {
// This block will execute when the exception occurs
[Link]("Caught an exception: " + [Link]());
[Link]("Error: Cannot divide by zero.");
}
[Link]("Program execution continues after the catch block.");
}
}
Expected Output / Sample Test Cases:
Attempting to divide...
Caught an exception: / by zero
Error: Cannot divide by zero.
Program execution continues after the catch block.
Observations:
MSN, BVCR Page 44
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What is an exception?
o Answer: An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
2. What is the purpose of the finally block?
oAnswer: The finally block is used to execute important code, such as closing
files or database connections, regardless of whether an exception occurs or
not. It is always executed after the try and any catch block.
3. What is the difference between checked and unchecked exceptions?
o Answer: Checked exceptions are exceptions that are checked at compile-
time (e.g., IOException). The programmer must handle them using try-
catch or declare them using throws. Unchecked exceptions (or runtime
exceptions, e.g., ArithmeticException, NullPointerException) are not checked
at compile-time and are usually caused by programming errors.
Experiment 8.b: Illustrating Multiple catch Clauses
Objective: To handle different types of exceptions using multiple, specific catch blocks.
Procedure:
1. Logic: A single try block can be followed by multiple catch blocks. When an
exception is thrown, Java matches it against each catch block in order. The
first catch block that can handle the exception type (or its superclass) is executed.
2. Create a Scanner for user input.
3. Place the input and calculation logic inside a try block.
4. Prompt the user to enter two numbers.
5. Attempt to divide them and print the result.
6. Add a catch block for InputMismatchException. Inside, print an error message like
"Error: Please enter valid integers."
7. Add another catch block for ArithmeticException. Inside, print "Error: Cannot divide
by zero."
8. Add a generic catch block for Exception at the end to catch any other potential
errors.
Example Code Snippet:
import [Link];
MSN, BVCR Page 45
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
import [Link];
public class MultipleCatchDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
[Link]("Enter the numerator: ");
int numerator = [Link]();
[Link]("Enter the denominator: ");
int denominator = [Link]();
int result = numerator / denominator;
[Link]("Result: " + result);
} catch (InputMismatchException e) {
[Link]("Error: Invalid input. Please enter integers only.");
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero.");
} catch (Exception e) {
[Link]("An unexpected error occurred: " + [Link]());
} finally {
[Link]();
[Link]("Scanner closed.");
}
}
}
Expected Output / Sample Test Cases:
Input: 10, abc -> Output: Error: Invalid input. Please enter integers only.
Input: 10, 0 -> Output: Error: Cannot divide by zero.
Input: 10, 2 -> Output: Result: 5
Observations:
MSN, BVCR Page 46
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What happens if you place catch(Exception e) before catch(ArithmeticException
e)?
o Answer: It will cause a compile-time error. The more specific exception
(ArithmeticException) would be unreachable because the more
general Exception block would catch it first. The order must be from most
specific to most general.
2. Can a try block exist without a catch block?
o Answer: Yes, but it must be followed by a finally block.
3. What is the Throwable class?
o Answer: Throwable is the root class of the entire exception hierarchy in Java.
Both Exception and Error are subclasses of Throwable.
Week 9: Custom Exceptions and Packages
Experiment 9.a: Causing Built-in Exceptions
Objective: To intentionally create situations that throw common built-in runtime exceptions
to better understand their causes.
Procedure:
1. Logic: Understanding how common exceptions
like ArrayIndexOutOfBoundsException and NullPointerException occur helps in
writing more defensive code.
2. ArrayIndexOutOfBoundsException:
o In a try block, create an integer array of a fixed size (e.g., 3).
o Attempt to access an element at an index that is out of bounds (e.g., arr[5]).
o Catch the ArrayIndexOutOfBoundsException and print a descriptive message.
3. NullPointerException:
o In a different try block, declare an object reference and set it
to null (e.g., String s = null;).
o Attempt to call a method on this null reference (e.g., [Link]()).
Catch the NullPointerException and print a descriptive message.
o
Example Code Snippet:
MSN, BVCR Page 47
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
public class BuiltInExceptionDemo {
public static void main(String[] args) {
// 1. Causing ArrayIndexOutOfBoundsException
try {
int[] arr = new int[3];
[Link]("Accessing element at index 5...");
int element = arr[5]; // This will throw the exception
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught Exception: Index is out of bounds for the array.");
}
[Link]("\n----------------\n");
// 2. Causing NullPointerException
try {
String s = null;
[Link]("Calling length() on a null string...");
int length = [Link](); // This will throw the exception
} catch (NullPointerException e) {
[Link]("Caught Exception: Cannot call a method on a null reference.");
}
}
}
Expected Output / Sample Test Cases:
Accessing element at index 5...
Caught Exception: Index is out of bounds for the array.
----------------
Calling length() on a null string...
Caught Exception: Cannot call a method on a null reference.
Observations:
MSN, BVCR Page 48
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What is the difference between an Error and an Exception in Java?
o Answer: Errors typically represent irrecoverable situations that should not be
caught by an application
(e.g., OutOfMemoryError, StackOverflowError). Exceptions represent
conditions that an application might want to catch and handle
(e.g., IOException, NullPointerException).
2. When does a NumberFormatException occur?
o Answer: It occurs when you try to convert a string into a numeric type, but
the string does not have the appropriate format
(e.g., [Link]("abc")).
3. Is NullPointerException a checked or unchecked exception?
o Answer: It is an unchecked (runtime) exception.
Experiment 9.b: Creation of User-Defined Exception
Objective: To create and use a custom exception class to represent application-specific
error conditions.
Procedure:
1. Logic: Custom exceptions make the code more readable and allow for specific
handling of errors unique to the application's domain.
2. Create a new class InvalidAgeException that extends Exception.
3. Inside this class, create a constructor that takes a String message and passes it to the
superclass constructor using super(message);.
4. Create another class VoterRegistration with a method void validateAge(int age)
throws InvalidAgeException.
5. Inside validateAge, check if the age is less than 18. If it is, throw new
InvalidAgeException("Age is less than 18, not eligible to vote.");. Otherwise, print a
success message.
6. In a main method, call validateAge inside a try block and provide a catch block
specifically for InvalidAgeException.
Example Code Snippet:
// Custom Exception Class
class InvalidAgeException extends Exception {
MSN, BVCR Page 49
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
public InvalidAgeException(String message) {
super(message);
}
}
class VoterRegistration {
public void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is less than 18, not eligible to vote.");
} else {
[Link]("Eligible to vote.");
}
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
VoterRegistration vr = new VoterRegistration();
// Test Cases
try {
[Link]("Validating age 25: ");
[Link](25);
[Link]("Validating age 16: ");
[Link](16);
} catch (InvalidAgeException e) {
[Link]("\nCaught custom exception: " + [Link]());
}
}
}
Expected Output / Sample Test Cases:
Validating age 25: Eligible to vote.
Validating age 16:
Caught custom exception: Age is less than 18, not eligible to vote.
Observations:
MSN, BVCR Page 50
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. Why should a custom exception class extend Exception or one of its subclasses?
o Answer: To be part of Java's exception handling mechanism.
Extending Exception makes it a checked exception, while
extending RuntimeException makes it an unchecked exception. This allows it
to be thrown and caught like any other standard exception.
2. What is the difference between throw and throws?
o Answer: The throw keyword is used to explicitly throw an instance of an
exception within a method. The throws keyword is used in a method's
signature to declare the types of checked exceptions that the method might
throw but does not handle itself.
3. When is it appropriate to create a custom exception?
o Answer: It is appropriate when you need to represent an error condition that
is specific to your application's business logic and is not adequately described
by Java's built-in exceptions
(e.g., InsufficientFundsException, InvalidProductCodeException).
Experiment 9.c: User-Defined Packages
Objective: To organize related classes and interfaces into a package, and to use them from
an external class.
Procedure:
1. Logic: Packages are used to avoid naming conflicts, to control access, and to make
related types easier to find. The package statement must be the first line in the
source file.
2. Create a directory structure, for example, my_app/com/mycompany/utils.
3. Inside the utils directory, create a Java file [Link].
4. At the top of [Link], declare the package: package [Link];.
5. Inside the StringUtils class, create a public static method String reverseString(String
str). This method should return the reversed version of the input string.
6. Create another Java file, [Link], outside the package directory (e.g.,
in my_app).
7. In [Link], use the import statement to import your class: import
[Link];.
8. In the main method of MainApp, call the static method
directly: [Link]("Hello World") and print the result.
MSN, BVCR Page 51
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
9. Compile and run from the top-level directory (my_app). Compile with javac
com/mycompany/utils/[Link] and javac [Link]. Run with java
MainApp.
Example Code Snippet:
File: my_app/com/mycompany/utils/[Link]
package [Link];
public class StringUtils {
public static String reverseString(String str) {
return new StringBuilder(str).reverse().toString();
}
}
File: my_app/[Link]
import [Link];
public class MainApp {
public static void main(String[] args) {
String original = "Java Packages";
// Test Case
String reversed = [Link](original);
[Link]("Original: " + original);
[Link]("Reversed: " + reversed);
}
}
Expected Output / Sample Test Cases:
Original: Java Packages
Reversed: segakcaP avaJ
Observations:
MSN, BVCR Page 52
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What is the purpose of the import keyword?
oAnswer: The import keyword is used to make classes and interfaces from
other packages available to the current source file without having to use their
fully qualified names.
2. What happens if you don't use a package statement in your file?
o Answer: The class or interface is placed in the "default package," which is a
package with no name. It is generally discouraged for real applications.
3. What is the CLASSPATH environment variable?
o Answer: CLASSPATH is an environment variable that tells the Java Virtual
Machine (JVM) and the Java compiler where to find the .class files for user-
defined classes and third-party libraries.
Week 10: File I/O and Advanced String Handling
Experiment 10.a: File Copy
Objective: To read content from a source text file and write it to a destination text file using
Java's I/O streams.
Procedure:
1. Logic: Java I/O uses streams to read from and write to data
sources. FileReader reads characters from a file, and FileWriter writes characters to
a file. Using them with BufferedReader and BufferedWriter improves performance
by reading/writing larger chunks of data at once.
2. Create a text file named [Link] and add some sample content to it.
3. In a main method, use a try-with-resources statement to automatically manage the
closing of streams.
4. Instantiate BufferedReader wrapped around a FileReader for the source file.
5. Instantiate BufferedWriter wrapped around a FileWriter for the destination file
([Link]).
6. Declare a String variable line. Use a while loop that continues as long as (line =
[Link]()) != null.
MSN, BVCR Page 53
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
7. Inside the loop, write the line to the destination file using [Link](line) and add
a new line with [Link]().
8. After the program runs, verify that [Link] has been created with the same
content as [Link].
Example Code Snippet:
import [Link].*;
public class FileCopyDemo {
public static void main(String[] args) {
String sourceFile = "[Link]";
String destFile = "[Link]";
// Create a sample source file for the test case
try (BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFile))) {
[Link]("Hello World.\n");
[Link]("This is a file copy demo.\n");
[Link]("Using BufferedReader and BufferedWriter.");
} catch (IOException e) {
[Link]("Error creating source file: " + [Link]());
}
// Perform the copy operation
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
[Link]();
}
[Link]("File copied successfully from " + sourceFile + " to " + destFile);
} catch (IOException e) {
[Link]("An error occurred during file copy: " + [Link]());
}
}
}
Expected Output / Sample Test Cases:
Console Output: File copied successfully from [Link] to [Link]
MSN, BVCR Page 54
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
File [Link] Content:
Hello World.
This is a file copy demo.
Using BufferedReader and BufferedWriter.
Observations:
Viva Questions:
1. What is the difference between a byte stream and a character stream?
o Answer: Byte streams (like FileInputStream, FileOutputStream) read and
write raw binary data one byte at a time. Character streams
(like FileReader, FileWriter) read and write character data, automatically
handling the conversion between characters and bytes based on the default
character encoding. Character streams are preferred for text files.
2. What is the purpose of the try-with-resources statement?
o Answer: It automatically closes resources (like streams) that implement
the AutoCloseable interface. This simplifies code and prevents resource leaks
by ensuring that close() is always called, even if exceptions occur.
3. Why are BufferedReader and BufferedWriter used?
o Answer: They improve performance. Instead of making a system call for
every single character read or written, they use an internal buffer to read or
write large chunks of data at once, reducing the number of I/O operations.
MSN, BVCR Page 55
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Experiment 10.b: Word Count
Objective: To read a text file and count the total number of words it contains.
Procedure:
1. Logic: The program will read the file line by line. For each line, it will split the line
into an array of words using a space as the delimiter. The length of this array gives
the word count for that line, which is then added to a running total.
2. Use the [Link] file created in the previous experiment.
3. In a main method, initialize an integer variable wordCount = 0.
4. Use a try-with-resources statement with a BufferedReader to read the file.
5. Use a while loop to read the file line by line.
6. Inside the loop, for each non-null line, use the [Link]("\\s+") method.
The "\\s+" is a regular expression that splits the string by one or more whitespace
characters (spaces, tabs, newlines).
7. This returns a String[] array. Add the length of this array to wordCount.
8. After the loop, print the final wordCount.
Example Code Snippet:
import [Link].*;
public class WordCountDemo {
public static void main(String[] args) {
String sourceFile = "[Link]"; // Assumes file from 10.a exists
int wordCount = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile))) {
String line;
while ((line = [Link]()) != null) {
// Split line by one or more whitespace characters
String[] words = [Link]("\\s+");
// Add the number of words found in this line to the total count
wordCount += [Link];
}
[Link]("Total word count in the file: " + wordCount);
} catch (FileNotFoundException e) {
[Link]("Error: File not found at " + sourceFile);
} catch (IOException e) {
[Link]("An error occurred while reading the file: " + [Link]());
}
}
}
MSN, BVCR Page 56
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Expected Output / Sample Test Cases:
For the [Link] created in 10.a: Total word count in the file: 12
For a file containing "one two three": Total word count in the file: 3
For an empty file: Total word count in the file: 0
Observations:
Viva Questions:
1. What does the regular expression "\\s+" mean?
o Answer: \s represents any whitespace character (space, tab, newline, etc.).
The + is a quantifier that means "one or more times." So, "\\s+" splits the
string wherever one or more whitespace characters occur together.
2. How would you handle a case where a file is very large and cannot fit into
memory?
o Answer: The current line-by-line reading approach is suitable for large files
because it only loads one line into memory at a time, not the entire file. This
is an efficient way to process large text files.
3. What is the File class in Java used for?
o Answer: The [Link] class is used to represent a file or directory path. It is
not used for reading/writing content but for operations like checking if a file
exists, creating a directory, deleting a file, or getting file metadata (like size
and last modified date).
Week 11: Multithreading - Part 1
Experiment 11.a: Creating Threads
Objective: To create and run multiple threads concurrently using both the Thread class and
the Runnable interface.
Procedure:
1. Logic: Multithreading allows a program to execute multiple tasks concurrently. A
thread can be created by extending the Thread class or, more commonly, by
implementing the Runnable interface.
2. Part 1: Extending Thread
MSN, BVCR Page 57
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Create a class MessageThread that extends Thread.
o Give it String message and int interval properties and a constructor.
o Override the run() method. Inside run(), use a while(true) loop. In the loop,
print the message and then call [Link](interval). Wrap the sleep call in
a try-catch block.
3. Part 2: Implementing Runnable
o Create a class MessageRunnable that implements Runnable. Follow the
same logic as Part 1 for properties, constructor, and the run() method.
4. Main Method:
o In main, first create and start() three instances of MessageThread.
o Then, comment that out and create three instances of MessageRunnable.
Pass each instance to a new Thread object's constructor (new
Thread(runnableObject)) and then start() those threads. Observe that the
output is similar.
Example Code Snippet (Implementing Runnable):
class MessageRunnable implements Runnable {
private String message;
private int interval;
public MessageRunnable(String message, int interval) {
[Link] = message;
[Link] = interval;
}
@Override
public void run() {
try {
while (true) {
[Link](message);
[Link](interval);
}
} catch (InterruptedException e) {
[Link](message + " thread was interrupted.");
}
}
}
public class MultiThreadDemo {
public static void main(String[] args) {
// Test Case using Runnable (preferred way)
MSN, BVCR Page 58
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Thread t1 = new Thread(new MessageRunnable("Good Morning", 1000));
Thread t2 = new Thread(new MessageRunnable("Hello", 2000));
Thread t3 = new Thread(new MessageRunnable("Welcome", 3000));
[Link]();
[Link]();
[Link]();
}
}
Expected Output / Sample Test Cases:
(Output will be an interleaved stream of messages, running continuously)
Good Morning
Hello
Welcome
Good Morning
Good Morning
Hello
...and so on.
Observations:
MSN, BVCR Page 59
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. Why is implementing Runnable preferred over extending Thread?
o Answer: Java does not support multiple inheritance of classes. If you
extend Thread, you cannot extend any other class. By
implementing Runnable, your class is free to extend another class, making it
more flexible. It also promotes better object-oriented design by separating
the task (Runnable) from the execution mechanism (Thread).
2. What is the difference between [Link]() and [Link]()?
o Answer: Calling start() creates a new thread and makes it eligible to be run
by the scheduler. The JVM then calls the run() method in that new thread. If
you call run() directly, it simply executes the method in the current thread,
just like any other normal method call, and no new thread is created.
3. What does [Link]() do?
o Answer: It pauses the execution of the current thread for a specified number
of milliseconds. It can throw an InterruptedException, which is a checked
exception.
Experiment 11.b: Thread Lifecycle Methods ( isAlive() and join() )
Objective: To use the isAlive() and join() methods to manage and coordinate the execution
of threads.
Procedure:
1. Logic: isAlive() checks if a thread is currently running. join() makes the current
thread wait until the thread it is called on terminates.
2. Create a Runnable task that simulates a long-running process by sleeping for a few
seconds.
3. In the main method, create and start two threads with this task.
4. Immediately after starting, use a for loop to print the status of both threads
using isAlive(). You will see true.
5. Call [Link]() and [Link](). Wrap these calls in a try-catch block
for InterruptedException. This will cause the main thread to pause and wait
for t1 and t2 to finish.
6. After the join() calls complete, print the status of the threads again using isAlive().
You will now see false.
7. Finally, print a message indicating all tasks are complete.
MSN, BVCR Page 60
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Example Code Snippet:
public class JoinDemo {
public static void main(String[] args) {
Runnable task = () -> {
try {
[Link]([Link]().getName() + " has started.");
[Link](2000);
[Link]([Link]().getName() + " has finished.");
} catch (InterruptedException e) {
[Link]();
}
};
Thread t1 = new Thread(task, "Worker-1");
Thread t2 = new Thread(task, "Worker-2");
[Link]("Starting threads...");
[Link]();
[Link]();
[Link]("Is Worker-1 alive? " + [Link]());
[Link]("Is Worker-2 alive? " + [Link]());
try {
[Link]("Main thread is waiting for worker threads to finish...");
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]();
}
[Link]("\nAfter join:");
[Link]("Is Worker-1 alive? " + [Link]());
[Link]("Is Worker-2 alive? " + [Link]());
[Link]("All tasks completed. Main thread is exiting.");
}
}
Expected Output / Sample Test Cases:
Starting threads...
Is Worker-1 alive? true
MSN, BVCR Page 61
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Is Worker-2 alive? true
Main thread is waiting for worker threads to finish...
Worker-1 has started.
Worker-2 has started.
(.. a 2-second pause ..)
Worker-1 has finished.
Worker-2 has finished.
After join:
Is Worker-1 alive? false
Is Worker-2 alive? false
All tasks completed. Main thread is exiting.
Observations:
Viva Questions:
1. What are the states in a thread's life cycle?
o Answer: The main states are: NEW (created but not
started), RUNNABLE (ready to
run), BLOCKED/WAITING/TIMED_WAITING (not running, waiting for a lock,
notification, or time to pass), and TERMINATED (finished execution).
2. What is the purpose of the join() method?
o Answer: It is used to ensure that a thread has completed its execution before
the program continues. It forces the currently running thread (e.g., the main
thread) to pause until the thread on which join() was called is dead.
3. What is the difference between join() and sleep()?
o Answer: sleep() pauses the current thread for a specified amount of
time. join() pauses the current thread to wait for another thread to
terminate.
MSN, BVCR Page 62
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Week 12: Multithreading - Part 2
Experiment 12.a: Daemon Threads
Objective: To understand and demonstrate the behavior of daemon threads, which do not
prevent the JVM from exiting.
Procedure:
1. Logic: Daemon threads are low-priority threads that run in the background to
provide services to user threads. The JVM exits as soon as all user (non-daemon)
threads have finished their execution; it does not wait for daemon threads.
2. Create a Runnable that runs an infinite loop, printing a message every second (e.g.,
"Daemon thread is running...").
3. In the main method, create a new Thread with this Runnable.
4. Crucially, before starting the thread, call [Link](true);.
5. Start the daemon thread.
6. In the main thread, print a message indicating that the main thread is running and
will exit in a few seconds, then call [Link]() for a short period (e.g., 3
seconds).
7. After the sleep, the main thread will finish. Observe that the entire application
terminates, and the daemon thread's infinite loop is abruptly stopped.
Example Code Snippet:
public class DaemonThreadDemo {
public static void main(String[] args) {
Runnable backgroundTask = () -> {
try {
while (true) {
[Link]("Daemon thread is running...");
[Link](1000);
}
} catch (InterruptedException e) {
// This will likely not be printed as the JVM will exit
[Link]("Daemon thread interrupted.");
}
};
Thread daemonThread = new Thread(backgroundTask);
[Link](true); // Set this thread as a daemon
[Link]();
try {
[Link]("Main thread (user thread) is running.");
MSN, BVCR Page 63
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link](3000); // Main thread lives for 3 seconds
[Link]("Main thread is finishing. JVM will now exit.");
} catch (InterruptedException e) {
[Link]();
}
}
}
Expected Output / Sample Test Cases:
Main thread (user thread) is running.
Daemon thread is running...
Daemon thread is running...
Daemon thread is running...
Main thread is finishing. JVM will now exit.
(Program terminates immediately)
Observations:
Viva Questions:
1. What is a daemon thread?
o Answer: A daemon thread is a background service provider for user threads.
Its life depends on the user threads; the JVM will exit if only daemon threads
are running.
2. Can you set a thread as a daemon thread after it has started?
o Answer: No. You must call setDaemon(true) before calling
the start() method. Attempting to do so after starting the thread will throw
an IllegalThreadStateException.
3. Give an example of a daemon thread in the JVM.
o Answer: The Garbage Collector (GC) is a classic example of a daemon thread.
It runs in the background to clean up unused objects but does not prevent
the application from exiting.
Experiment 12.b: Producer-Consumer Problem
MSN, BVCR Page 64
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Objective: To solve the classic producer-consumer problem using synchronized, wait(),
and notify() for inter-thread communication.
Procedure:
1. Logic: A producer thread adds items to a shared buffer, and a consumer thread
removes them. They must be synchronized to prevent the producer from adding to a
full buffer and the consumer from removing from an empty one.
2. Create a SharedBuffer class with a LinkedList and a capacity limit.
3. Implement a synchronized void produce(int item) method. Inside a while loop,
check if the buffer is full. If so, call wait(). If not, add the item and call notifyAll().
4. Implement a synchronized int consume() method. Inside a while loop, check if the
buffer is empty. If so, call wait(). If not, remove and return the item, then
call notifyAll().
5. Create a Producer Runnable that calls [Link]().
6. Create a Consumer Runnable that calls [Link]().
7. In main, create the shared buffer, a producer thread, and a consumer thread, and
start them.
Example Code Snippet:
import [Link];
import [Link];
class SharedBuffer {
private Queue<Integer> buffer = new LinkedList<>();
private int capacity;
public SharedBuffer(int capacity) { [Link] = capacity; }
public synchronized void produce(int item) throws InterruptedException {
while ([Link]() == capacity) {
[Link]("Buffer is full. Producer is waiting...");
wait();
}
[Link](item);
[Link]("Producer produced: " + item);
notifyAll(); // Notify consumer that an item is available
}
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer is empty. Consumer is waiting...");
wait();
MSN, BVCR Page 65
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
}
int item = [Link]();
[Link]("Consumer consumed: " + item);
notifyAll(); // Notify producer that space is available
return item;
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer(2);
// Producer Thread
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
[Link](i);
[Link](500);
}
} catch (InterruptedException e) { [Link](); }
}).start();
// Consumer Thread
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
[Link]();
[Link](1500);
}
} catch (InterruptedException e) { [Link](); }
}).start();
}
}
Expected Output / Sample Test Cases:
(Output will show the interleaved and synchronized actions of the producer and consumer)
Producer produced: 1
Producer produced: 2
Buffer is full. Producer is waiting...
Consumer consumed: 1
Producer produced: 3
Consumer consumed: 2
MSN, BVCR Page 66
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Buffer is full. Producer is waiting...
... and so on
Observations:
Viva Questions:
1. Why must wait(), notify(), and notifyAll() be called from within a synchronized
context?
o Answer: These methods are used to manage the lock on an object. A thread
must own the object's monitor (lock) before it can release it (wait()) or signal
other waiting threads (notify()/notifyAll()). This ownership is acquired by
entering a synchronized method or block.
2. What is the difference between notify() and notifyAll()?
o Answer: notify() wakes up a single, arbitrary thread that is waiting on the
object's monitor. notifyAll() wakes up all threads that are waiting on the
object's monitor. It is generally safer to use notifyAll() to avoid situations
where the wrong thread is notified and a "missed signal" occurs.
3. What is a "spurious wakeup"? Why is it important to use wait() inside
a while loop?
o Answer: A spurious wakeup is a rare event where a thread can wake up from
a wait() call without being notified by notify() or notifyAll(). By placing
MSN, BVCR Page 67
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
the wait() call inside a while loop that re-checks the condition (e.g., while
([Link]())), the thread will correctly go back to waiting if it wakes up
prematurely.
Week 13: Java Database Connectivity (JDBC)
Experiment 13.a: Database Connection
Objective: To establish a connection to a MySQL database using the JDBC API.
Procedure:
1. Prerequisites:
o Ensure MySQL Server is installed and running.
o Create a database (e.g., universitydb) and a table (students).
o Download the MySQL JDBC driver (.jar file) and add it to your project's
classpath/build path.
2. Logic: JDBC involves 4 main steps: (1) Loading the driver, (2) Establishing a
connection, (3) Creating a statement, and (4) Executing the query. For this
experiment, we will focus on the first two.
3. Define constants for the database URL, username, and password. The URL format
is jdbc:mysql://hostname:port/databaseName.
4. In a main method, use a try-with-resources block for the Connection object to
ensure it is automatically closed.
5. Establish the connection using [Link](URL, USER, PASS);.
6. If the connection is successful (no exception is thrown), print a success message.
7. Include a catch block for SQLException to handle any potential connection errors.
Example Code Snippet:
import [Link];
import [Link];
import [Link];
public class DbConnectionDemo {
// Replace with your database credentials
private static final String URL = "jdbc:mysql://localhost:3306/universitydb";
private static final String USER = "root";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try (Connection connection = [Link](URL, USER, PASSWORD)) {
if (connection != null) {
MSN, BVCR Page 68
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link]("Connection to database established successfully!");
}
} catch (SQLException e) {
[Link]("Failed to connect to the database.");
[Link]();
}
}
}
Expected Output / Sample Test Cases:
Success: Connection to database established successfully!
Failure (e.g., wrong password): An error message and a stack trace
for SQLException.
Observations:
Viva Questions:
1. What is JDBC?
o Answer: JDBC (Java Database Connectivity) is a standard Java API for
connecting and executing queries with a database. It provides a common
interface, allowing a Java program to interact with various relational
databases using a specific driver for each.
2. What is the role of the JDBC Driver?
o Answer: A JDBC driver is a software component that enables a Java
application to interact with a specific database. It acts as a translator,
converting JDBC calls from the Java program into the database's native
protocol and vice-versa.
3. What is the difference between Statement and PreparedStatement?
o Answer: Statement is used for executing simple, static SQL
queries. PreparedStatement is used for executing precompiled SQL queries
with parameters (?). PreparedStatement is generally preferred because it is
more secure (prevents SQL injection) and often performs better for repeated
queries.
MSN, BVCR Page 69
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Experiment 13.b: Inserting and Updating Data
Objective: To use JDBC PreparedStatement to insert and update records in a database
table.
Procedure:
1. Prerequisites: A students table in your database with columns like id (INT, PRIMARY
KEY, AUTO_INCREMENT), name (VARCHAR), and major (VARCHAR).
2. Logic: Use a PreparedStatement with placeholders (?) for data values. This
precompiles the SQL query and safely inserts the data by setting the values for each
placeholder.
3. Insert:
o Establish a database connection.
o Define an INSERT SQL query string: INSERT INTO students (name, major)
VALUES (?, ?);.
o Create a PreparedStatement and set the values for the placeholders using
methods like [Link]().
Execute the statement using [Link]().
o
4. Update:
o Follow the same logic but use an UPDATE SQL query string: UPDATE students
SET major = ? WHERE id = ?;.
o Set the values for the new major and the student ID.
5. Use a try-with-resources block for all JDBC resources.
Example Code Snippet:
import [Link].*;
public class DataManipulationDemo {
private static final String URL = "jdbc:mysql://localhost:3306/universitydb";
private static final String USER = "root";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
// --- Test Case 1: Inserting Data ---
try (Connection conn = [Link](URL, USER, PASSWORD);
PreparedStatement stmt = [Link]("INSERT INTO students (name,
major) VALUES (?, ?)")) {
[Link](1, "Jane Doe");
[Link](2, "Computer Science");
int rowsAffected = [Link]();
MSN, BVCR Page 70
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
[Link](rowsAffected + " row(s) inserted successfully.");
} catch (SQLException e) { [Link](); }
[Link]("\n----------------\n");
// --- Test Case 2: Updating Data ---
try (Connection conn = [Link](URL, USER, PASSWORD);
PreparedStatement stmt = [Link]("UPDATE students SET major = ?
WHERE id = ?")) {
[Link](1, "Information Technology");
[Link](2, 1); // Assuming a student with id=1 exists
int rowsAffected = [Link]();
[Link](rowsAffected + " row(s) updated successfully.");
} catch (SQLException e) { [Link](); }
}
}
Expected Output / Sample Test Cases:
1 row(s) inserted successfully.
----------------
1 row(s) updated successfully.
(Verify changes directly in the MySQL database)
Observations:
MSN, BVCR Page 71
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Viva Questions:
1. What does the executeUpdate() method return?
o Answer: It returns an int representing the number of rows affected by the
SQL statement (for INSERT, UPDATE, or DELETE), or 0 for SQL statements
that return nothing (like DDL statements).
2. What is SQL Injection and how does PreparedStatement prevent it?
o Answer: SQL Injection is an attack where malicious SQL code is inserted into a
query. PreparedStatement prevents this by treating user-supplied input as
literal values, not as part of the executable SQL command. The driver handles
the safe escaping of characters.
3. What is a transaction in JDBC?
o Answer: A transaction is a sequence of operations performed as a single
logical unit of work. By default, JDBC is in auto-commit mode, meaning each
statement is a transaction. You can disable this ([Link](false))
to group multiple statements together. You can then commit() the
transaction if all succeed or rollback() if any fail.
Week 14: JavaFX GUI & Event Handling
Experiment 14.a: Building a Basic GUI with JavaFX and FXML
Objective: To create a simple GUI using Scene Builder (FXML) and load it in a JavaFX
application without writing UI code in Java.
Procedure:
1. Prerequisites: Scene Builder application installed and configured with your IDE.
2. Logic: FXML is an XML-based language that allows you to define the structure of a
user interface separately from the application logic. This promotes a clean Model-
View-Controller (MVC) architecture.
3. Scene Builder:
o Open Scene Builder and drag a Label and an ImageView onto the main pane
(e.g., an AnchorPane).
o Set the text for the Label (e.g., "Welcome to JavaFX!").
o For the ImageView, set the image property by selecting a sample image file
from your project directory.
MSN, BVCR Page 72
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Save the file as [Link] inside your
project's src/main/resources folder.
4. Java Code:
o Create a main application class that extends [Link].
o In the start(Stage primaryStage) method, use FXMLLoader to load
the [Link] file.
o Create a Scene from the loaded FXML root.
o Set the scene on the primaryStage and call [Link]().
Example Code Snippet:
File: src/main/resources/[Link] (Generated by Scene Builder)
Generated xml
<?xml version="1.0" encoding="UTF-8"?>
<?import [Link]?>
<?import [Link]?>
<?import [Link]?>
<?import [Link]?>
<AnchorPane prefHeight="300.0" prefWidth="400.0" xmlns="[Link]
xmlns:fx="[Link]
<children>
<Label layoutX="136.0" layoutY="31.0" text="Welcome to JavaFX!" />
<ImageView fitHeight="150.0" fitWidth="200.0" layoutX="100.0" layoutY="83.0"
pickOnBounds="true" preserveRatio="true">
<image>
<Image url="@/path/to/your/[Link]" />
</image>
</ImageView>
</children>
</AnchorPane>
File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
MSN, BVCR Page 73
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Parent root = [Link](getClass().getResource("/[Link]"));
[Link]("Simple FXML App");
[Link](new Scene(root));
[Link]();
}
public static void main(String[] args) {
launch(args);
}
}
Expected Output: A window displaying the text "Welcome to JavaFX!" and the image you
selected.
Observations:
Viva Questions:
1. What is FXML?
o Answer: FXML is an XML-based markup language for defining the user
interface of a JavaFX application. It allows for separating the UI design (the
"view") from the application logic (the "controller").
2. What is a Stage and a Scene in JavaFX?
o Answer: The Stage is the top-level container, typically representing a
window. The Scene is the container for all content inside a Stage.
A Stage holds one Scene at a time. The content itself is organized in a "scene
graph."
3. What is Scene Builder?
o Answer: Scene Builder is a visual design tool that allows developers to create
and modify FXML files by dragging and dropping UI components, simplifying
the process of designing a JavaFX GUI.
MSN, BVCR Page 74
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Experiment 14.b: Building an Interactive Tip Calculator
Objective: To build a functional GUI application with event handling to respond to user
interactions.
Procedure:
1. Logic: Event handling in JavaFX involves assigning methods in a controller class
to onAction (or similar) events of UI components defined in FXML.
The @FXML annotation links FXML components to variables in the controller.
2. Scene Builder (FXML):
o Design a UI with a TextField (give it an fx:id, e.g., billField),
a Slider (e.g., tipSlider), a Button (e.g., calculateButton), and two Labels
(e.g., tipAmountLabel, totalBillLabel).
o In the "Controller" section of Scene Builder, specify the name of your
controller class (e.g., TipCalculatorController).
o For the button, set its On Action property to a method name,
e.g., handleCalculateButton.
3. Controller Class (Java):
o Create [Link].
o Declare variables for each UI component with an fx:id, annotating them
with @FXML.
o Create the void handleCalculateButton(ActionEvent event) method.
o Inside this method, get the text from the billField, parse it to a double.
o Get the value from the tipSlider.
o Calculate the tip and total bill.
o Update the text of the result labels.
4. Load the FXML in your main application class as before.
Example Code Snippet:
File: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TipCalculatorController {
@FXML private TextField billField;
@FXML private Slider tipSlider;
@FXML private Label tipAmountLabel;
@FXML private Label totalBillLabel;
MSN, BVCR Page 75
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
@FXML
void handleCalculateButton(ActionEvent event) {
try {
double bill = [Link]([Link]());
double tipPercentage = [Link]();
double tipAmount = bill * (tipPercentage / 100);
double totalBill = bill + tipAmount;
[Link]([Link]("$%.2f", tipAmount));
[Link]([Link]("$%.2f", totalBill));
} catch (NumberFormatException e) {
[Link]("Invalid");
[Link]("Input");
}
}
}
Expected Output: A functional tip calculator window. Entering a bill amount and clicking the
button calculates and displays the tip and total.
Observations:
Viva Questions:
1. What is the role of a Controller class in JavaFX MVC?
o Answer: The Controller class contains the application logic and event
handlers for the UI. It acts as the bridge between the View (FXML) and the
Model (data).
2. What does the @FXML annotation do?
o Answer: It is used to inject values defined in an FXML file into corresponding
fields in the controller class. It links the UI components created in Scene
Builder to the variables in your Java code.
3. What is an ActionEvent?
o Answer: An ActionEvent is an event that indicates a component-defined
action occurred. It is most commonly generated by a user clicking a Button or
pressing Enter in a TextField.
MSN, BVCR Page 76
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Week 15 & 16: Mini-Project
Experiment 15.a: Final Project - Student Management System
Objective: To integrate all learned concepts (OOP, JDBC, JavaFX) to build a complete CRUD
(Create, Read, Update, Delete) desktop application.
Procedure:
1. Logic: The application will use a DAO (Data Access Object) pattern to separate
database logic from the UI logic. The JavaFX front-end will display data in
a TableView and use separate windows (dialogs) for adding and editing records.
2. Week 15 - Backend and UI Design:
o Database: Finalize your students table schema in MySQL.
o DAO Class: Create a [Link] class. Implement the following static
methods, each handling its own JDBC connection and statements:
ObservableList<Student> getAllStudents(): Fetches all records and
returns them in an ObservableList.
void addStudent(Student student): Inserts a new student record.
void updateStudent(Student student): Updates an existing record.
void deleteStudent(int id): Deletes a record by ID.
o Model Class: Create a [Link] class with properties matching the table
columns (IntegerProperty, StringProperty, etc.).
o UI Design: In Scene Builder, design the main window ([Link]) with
a TableView and buttons for "Add," "Edit," and "Delete." Design a separate
window ([Link]) with TextFields and a "Save" button for
adding/editing students.
3. Week 16 - Integration and Completion:
o Main Controller: Create [Link]. In its initialize() method,
configure the TableView columns and call [Link]() to
populate the table.
o Event Handling:
Implement the "Add" button handler to open
the [Link] window.
Implement the "Edit" button handler to open
the [Link] window, passing the selected student's data to pre-
fill the fields.
Implement the "Delete" button handler to get the selected student's
ID and call [Link]().
MSN, BVCR Page 77
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
o Edit Controller: Create [Link]. The "Save" button handler
will either
call [Link]() or [Link]() based on
whether it's in "add" or "edit" mode, and then close the window.
o Refresh Logic: After any CUD operation, refresh the TableView in the main
window by re-fetching the data from the database.
Expected Output:
A fully functional desktop application where a user can view a list of students from a
database, and add, edit, or delete student records, with all changes reflected in both the UI
and the underlying MySQL database.
Observations:
Overall Viva Questions for OOP Through Java Lab
Category 1: Core Java and Language Fundamentals
1. What is the difference between JDK, JRE, and JVM?
o Answer: JVM (Java Virtual Machine) is an abstract machine that
provides the runtime environment in which Java bytecode can be
executed. JRE (Java Runtime Environment) is the implementation
of the JVM; it contains the JVM, libraries, and other files needed
to run Java programs. JDK (Java Development Kit) is the full-
featured development kit; it includes the JRE plus development
tools like the compiler (javac) and debugger.
2. Why is Java called "platform-independent"?
MSN, BVCR Page 78
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Answer: Because the Java compiler converts source code into
o
platform-independent bytecode, not machine-specific code. This
bytecode can then be run on any machine that has a Java Virtual
Machine (JVM), regardless of the underlying operating system or
hardware.
3. What are primitive data types in Java? What are their default values?
o Answer: There are 8 primitive
types: byte (0), short (0), int (0), long (0L), float (0.0f), double (0.0d
), char ('\u0000'), and boolean (false).
4. What is the difference between == and the .equals() method?
o Answer: The == operator checks if two reference variables point
to the exact same object in memory (reference comparison).
The .equals() method, when properly overridden, checks if two
objects are meaningfully or logically equivalent (content
comparison). For String, .equals() compares the character
sequences.
5. What is the difference between String, StringBuilder, and StringBuffer?
o Answer:
String: Immutable. A new object is created for every
modification.
StringBuffer: Mutable and thread-safe (synchronized).
Slower due to synchronization overhead.
StringBuilder: Mutable and not thread-safe. Faster
than StringBuffer and should be used in single-threaded
environments.
Category 2: Object-Oriented Programming (OOP) Principles
1. What are the four main principles of OOP? Explain each briefly.
o Answer:
Encapsulation: Binding data (variables) and the code that
manipulates it (methods) into a single unit (a class). It's
implemented using access modifiers (private) to hide data.
Inheritance: A mechanism where a new class (subclass)
acquires the properties and behaviors of an existing class
(superclass). It promotes code reuse and an "is-a"
relationship.
MSN, BVCR Page 79
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Polymorphism: The ability of an object to take on many
forms. In Java, this is achieved through method overloading
(compile-time) and method overriding (run-time).
Abstraction: Hiding complex implementation details and
showing only the essential features of an object. It's
achieved using abstract classes and interfaces.
2. What is a constructor? Can it be inherited?
o Answer: A constructor is a special method used to initialize an
object when it is created. It has the same name as the class and no
return type. Constructors are not inherited, but a subclass
constructor must call a superclass constructor using super().
3. What is method overloading vs. method overriding?
o Answer:
Overloading: Occurs in the same class. Multiple methods
have the same name but different parameters (number,
type, or order). It is compile-time polymorphism.
Overriding: Occurs in two classes with an inheritance
relationship. The subclass provides a specific
implementation for a method that is already defined in its
superclass. It is run-time polymorphism.
4. What is the final keyword? How can it be used with a variable, method,
and class?
o Answer:
final variable: Creates a constant. Its value cannot be
changed once assigned.
final method: Cannot be overridden by a subclass.
final class: Cannot be extended (inherited from).
5. Explain the difference between an abstract class and an interface.
o Answer:
An abstract class can have both abstract and non-abstract
methods and instance variables. A class can extend only one
abstract class. It's used when there is a strong "is-a"
relationship and you want to provide some base
implementation.
MSN, BVCR Page 80
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
An interface (before Java 8) could only have abstract
methods. A class can implement multiple interfaces. It's
used to define a "can-do" contract or capability for a class.
Category 3: Exception Handling and Packages
1. What is the difference between a checked and an unchecked
exception?
o Answer: Checked exceptions are checked at compile-time
(e.g., IOException, SQLException). You must handle them with try-
catch or declare them with throws. Unchecked
exceptions (runtime exceptions) are not checked at compile-time
and usually result from programming errors
(e.g., NullPointerException, ArithmeticException).
2. What is the purpose of the try, catch, and finally blocks?
o Answer:
try: Encloses code that might throw an exception.
catch: Catches and handles a specific type of exception
thrown from the try block.
finally: Contains code that is always executed, whether an
exception was thrown or not. It's used for cleanup, like
closing resources.
3. What is the difference between throw and throws?
o Answer: The throw keyword is used to manually throw an
exception object within a method. The throws keyword is used in
a method's signature to declare that the method might throw
certain checked exceptions, passing the responsibility of handling
them to the calling method.
4. Why would you create a user-defined (custom) exception?
o Answer: To represent application-specific errors that are not
covered by Java's built-in exceptions. This makes the code more
readable and allows for specific error handling
(e.g., InsufficientFundsException).
5. What is a package in Java and why is it used?
o Answer: A package is a namespace that organizes a set of related
classes and interfaces. They are used to prevent naming conflicts,
MSN, BVCR Page 81
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
to control access (protected, default access), and to make the
code more maintainable.
Category 4: Multithreading
1. What are the two ways to create a thread? Which one is preferred and
why?
o Answer: 1. By extending the Thread class. 2. By implementing
the Runnable interface. Implementing Runnable is preferred
because Java does not support multiple class inheritance, so it
allows your class to extend another class while still being
runnable. It also promotes better design by separating the task
from the runner.
2. Explain the difference between [Link]() and [Link]().
o Answer: start() creates a new thread of execution and tells the
JVM to call the run() method in that new thread. run() is just a
normal method; calling it directly will execute its code in the
current thread, not a new one.
3. What is the purpose of the synchronized keyword?
o Answer: It is used to create a "monitor" or "lock" on an object,
ensuring that only one thread can execute a synchronized block of
code or method on that object instance at a time. It prevents race
conditions and ensures data consistency in a multi-threaded
environment.
4. Explain the purpose of wait(), notify(), and notifyAll().
o Answer: These methods are used for inter-thread communication.
wait(): Causes the current thread to release the lock and
wait until another thread invokes notify() or notifyAll() on
the same object.
notify(): Wakes up a single thread that is waiting on the
object's lock.
notifyAll(): Wakes up all threads waiting on the object's
lock.
5. What is a daemon thread?
o Answer: A daemon thread is a low-priority background thread
that provides services to user threads. The JVM will exit when all
MSN, BVCR Page 82
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
user threads are finished, regardless of whether daemon threads
are still running. The Garbage Collector is an example.
Category 5: File I/O, JDBC, and JavaFX
1. What is the difference between a byte stream and a character stream
in Java I/O?
o Answer: Byte streams (e.g., FileInputStream) handle raw binary
data (like images or executables). Character
streams (e.g., FileReader) handle text data, automatically
managing character encoding.
2. What is JDBC and what are the main steps to connect to a database?
o Answer: JDBC is the Java Database Connectivity API. The main
steps are:
1. Load the JDBC driver.
2. Establish a connection
using [Link]().
3. Create a Statement or PreparedStatement object.
4. Execute the query.
5. Process the ResultSet (for SELECT queries).
6. Close all resources (ResultSet, Statement, Connection).
3. How does PreparedStatement help prevent SQL injection?
o Answer: It pre-compiles the SQL query and treats user input as
literal data, not as part of the executable SQL command. The
driver handles the necessary escaping of characters, making it
impossible for malicious SQL code to be executed.
4. What is FXML and why is it used in JavaFX?
o Answer: FXML is an XML-based markup language used to define
the user interface of a JavaFX application. It is used to separate
the presentation layer (the view) from the application logic (the
controller), promoting a clean Model-View-Controller (MVC)
design.
5. What is the role of the DAO (Data Access Object) pattern in the mini-
project?
o Answer: The DAO pattern isolates the database access logic from
the rest of the application (the business logic and UI logic). It
provides a dedicated class with methods for all CRUD (Create,
MSN, BVCR Page 83
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
Read, Update, Delete) operations, making the code more
modular, easier to test, and simpler to maintain or switch
databases later.
SPACE FOR NOTES AND OBSERVATIONS:
SPACE FOR NOTES AND OBSERVATIONS:
MSN, BVCR Page 84
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
SPACE FOR NOTES AND OBSERVATIONS:
MSN, BVCR Page 85
ORBEJECT ORIENTED PROGRAMMING THROUGH JAVA
SPACE FOR NOTES AND OBSERVATIONS:
MSN, BVCR Page 86