Java Assignment Part 3
Java Assignment Part 3
rul er
sia
ha
az n
m u
ni
a
ve
an
rsi
Maul
Patna Bihar
ty
BCA Part – III
2022-2025
Java
Acknowledgement:
I sincerely thank my respected teacher for their guidance and support during the preparation of this Java
assignment.
I am also grateful to Maulana Mazharul Haque Arabic & Persian University for providing the resources and
Lastly, I appreciate my friends and family for their constant motivation throughout this journey.
Saptarshi Roy
Introduction:
Java is one of the most widely used and versatile programming languages in the world. It is an object-
oriented, platform-independent, and robust language that enables developers to create secure, reliable, and
efficient applications. Due to its “write once, run anywhere” capability, Java is extensively used in desktop
This assignment is aimed at applying the core concepts of Java, such as classes and objects,
inheritance, polymorphism, exception handling, interfaces, and file handling, to solve practical problems. By
working on this project, I was able to enhance my understanding of Java programming, improve my coding
skills, and gain hands-on experience in developing efficient solutions using Java.
Through this assignment, I also learned the importance of logical thinking, debugging, and proper
documentation while writing programs, which will help me in my future academic and professional journey.
Table of Contents:
• Chapter 1: Introduction to Java and Programming Concepts
Programming is providing instructions to a computer to perform a task. It's like writing a recipe. The computer
follows your instructions (the program) step-by-step. Computers are powerful but need clear, specific
instructions.
Java is a popular, object-oriented programming language. Created by James Gosling at Sun Microsystems (now
Oracle). Known for:
1. Platform Independence: "Write Once, Run Anywhere" (WORA). Works on any system with the Java
Virtual Machine (JVM).
2. Object-Oriented: Uses objects and classes.
3. Simple: Relatively easy to learn.
4. Robust and Secure: Handles errors and security threats.
5. Versatile: Used for web, mobile (Android), enterprise apps.
The JVM is like a translator. Java code is compiled into bytecode, which the JVM then converts into
instructions the computer can understand. This makes Java platform-independent.
The JDK is the set of tools you need to develop Java programs. It includes the compiler, JVM, and other
utilities.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Explanation:
1. public class HelloWorld: Defines a class named HelloWorld. All Java code lives inside classes.
2. public static void main(String[] args): The main method is the starting point of the program.
3. [Link]("Hello, World!");: Prints the text to the console.
1. Download: Go to Oracle's website or Adoptium (Eclipse Temurin) and download the JDK for your
operating system.
2. Install: Run the installer and follow the instructions.
3. Environment Variables: Crucially important!
1. JAVA_HOME: Points to the JDK installation directory.
2. PATH: Includes $JAVA_HOME/bin (Linux/macOS) or %JAVA_HOME%\bin (Windows) so you can
run java and javac from anywhere.
Windows Example:
1. Right-click "This PC" -> Properties -> Advanced system settings -> Environment Variables.
2. Create a new System variable JAVA_HOME with the JDK path (e.g., C:\Program Files\Java\jdk-17).
3. Edit the Path variable and add %JAVA_HOME%\bin.
macOS/Linux Example:
bash<button><svg><path></path></svg><span>Copy code</span><span></span></button>
export JAVA_HOME=/path/to/jdk
export PATH=$JAVA_HOME/bin:$PATH
• Verify: Open a new command prompt/terminal and type java -version and javac -version. You should
see version information.
1. Download: Download "Eclipse IDE for Java Developers" from the Eclipse website.
2. Extract: Unzip the downloaded file.
3. Run: Run [Link] (Windows) or the eclipse executable (macOS/Linux).
4. Create a Project: File -> New -> Java Project.
5. Create a Class: Right-click src -> New -> Class.
6. Write Code: Type your Java code in the class editor.
7. Run: Right-click in the editor -> Run As -> Java Application.
A variable is a named storage location. You must declare the type of data it will hold.
Declaration:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
dataType variableName;
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int age; // Declares an integer variable named 'age'
String name; // Declares a String variable named 'name'
Initialization:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
age = 25; // Assigns the value 25 to the 'age' variable
name = "Alice"; // Assigns the string "Alice" to the 'name' variable
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int age = 25;
String name = "Alice";
3.3 Operators
Symbols that perform operations.
Operators have an order of precedence (like in math). Use parentheses () to force a specific order. Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int result = 5 + 3 * 2; // result will be 11 (multiplication before addition)
int result2 = (5 + 3) * 2; // result2 will be 16 (parentheses first)
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
if (condition) {
// Code to execute if the condition is true
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int age = 18;
if (age >= 18) {
[Link]("You are eligible to vote.");
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int age = 15;
if (age >= 18) {
[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote yet.");
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int score = 75;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: D");
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
if (condition1) {
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
switch (variable) {
case value1:
// Code to execute if variable == value1
break; // Important! Prevents "fall-through"
case value2:
// Code to execute if variable == value2
break;
default:
// Code to execute if variable doesn't match any case
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
}
[Link](dayName); // Output: Wednesday
Used when you know how many times you want to repeat a block of code.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (initialization; condition; increment/decrement) {
// Code to execute repeatedly
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < 5; i++) {
[Link]("Iteration: " + i);
}
Explanation:
1. initialization: int i = 0; Creates a counter variable i and sets it to 0. Executed only once at the beginning.
2. condition: i < 5; The loop continues as long as i is less than 5.
3. increment/decrement: i++; Increases the value of i by 1 after each iteration.
Used when you want to repeat a block of code as long as a condition is true.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
while (condition) {
// Code to execute repeatedly
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int count = 0;
while (count < 5) {
[Link]("Count: " + count);
count++; // Important! Otherwise, the loop will run forever!
}
Similar to while, but the code block is executed at least once before the condition is checked.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
do {
// Code to execute repeatedly
} while (condition);
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int number = 10;
do {
[Link]("Number: " + number);
number--;
} while (number > 0);
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
[Link](i);
}
Skips the current iteration of a loop and proceeds to the next iteration.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
[Link](i); // Prints only odd numbers
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link]("i: " + i + ", j: " + j);
}
}
1. Class: A blueprint or template for creating objects. It defines the attributes (data) and behaviors
(methods) that objects of that class will have.
2. Object: An instance of a class. It's a real-world entity that has state (data) and behavior (methods).
Analogy:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class Dog {
// Attributes (instance variables)
String breed;
String name;
int age;
// Methods (behaviors)
public void bark() {
[Link]("Woof!");
}
Explanation:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
Dog myDog = new Dog(); // Creates a new Dog object
Use the dot operator (.) to access the attributes and methods of an object.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
[Link] = "Golden Retriever";
[Link] = "Buddy";
[Link] = 3;
Defining a Method:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public returnType methodName(parameterList) {
// Method body (code to execute)
return returnValue; // If the returnType is not void
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class Calculator {
public int add(int a, int b) {
int sum = a + b;
return sum;
}
}
Explanation:
Calling a Method:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
Calculator calc = new Calculator();
int result = [Link](5, 3); // Calls the add() method with arguments 5 and 3
[Link](result); // Output: 8
• Instance Methods: Operate on a specific object. They have access to the object's instance variables.
The bark() and displayInfo() methods in the Dog class are instance methods.
• Static Methods: Belong to the class itself, not to any specific object. You can call them directly using
the class name.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class MathUtils {
public static int square(int x) {
return x * x;
}
}
int squaredValue = [Link](4); // Call the static method using the class name
Defining multiple methods with the same name but different parameters.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class Overloader {
public int add(int a, int b) {
return a + b;
}
The compiler knows which add method to call based on the arguments you pass.
7.4 Constructors
Special methods that are called when an object is created. They initialize the object's state.
Defining a Constructor:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public class Person {
String name;
int age;
Explanation:
1. public Person(String name, int age): A constructor that takes a name and an age as parameters.
2. [Link] = name;: Assigns the parameter name to the instance variable name. this refers to the
current object.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
Person person1 = new Person("Bob", 30); // Creates a new Person object using the constructor
Declaring an Array:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
dataType[] arrayName;
Creating an Array:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
arrayName = new dataType[arraySize];
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int[] numbers = new int[5]; // Creates an integer array of size 5
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int[] numbers = {10, 20, 30, 40, 50}; // Creates and initializes an array in one step
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int firstNumber = numbers[0]; // firstNumber will be 10
Array Length:
Use the length property to get the number of elements in the array.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int arrayLength = [Link]; // arrayLength will be 5
Looping Through an Array:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
Arrays of arrays.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
int[][] matrix = new int[3][3]; // Creates a 3x3 matrix
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
String is a class in Java used to represent sequences of characters. Important: Strings are immutable in Java.
This means that once a String object is created, its value cannot be changed.
Creating Strings:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
String message = "Hello, World!";
String emptyString = "";
String Methods:
String Concatenation:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // fullName will be "John Doe"
String Immutability:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
String text = "Hello";
text = text + ", World!"; // A new String object is created, text now references it. The original "Hello" String is unchanged.
Chapter 9: Inheritance and Polymorphism
Inheritance allows you to create new classes (subclasses or derived classes) based on existing classes
(superclasses or base classes). The subclass inherits the attributes and methods of the superclass.
Keywords:
Syntax:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Subclass extends Superclass {
// Subclass attributes and methods
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Animal {
String name;
Explanation:
1. Single Inheritance: A class can inherit from only one superclass. (Java enforces this for classes directly).
9.3 Method Overriding
A subclass can provide its own implementation of a method that is already defined in the superclass. This is
called method overriding.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Animal {
public void makeSound() {
[Link]("Generic animal sound");
}
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Animal {
String name;
@Override
public void eat() {
[Link](); // Calls the Animal's eat() method
[Link]("Dog is eating a bone");
}
}
9.5 Polymorphism: Many Forms
1. Method Overriding (Runtime Polymorphism): The correct method to call is determined at runtime
based on the actual type of the object.
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
Animal animal1 = new Animal("Generic Animal");
Animal animal2 = new Dog("Buddy", "Golden Retriever");
Exceptions are events that disrupt the normal flow of program execution. They represent errors or unusual
conditions.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to execute if an exception of type ExceptionType is thrown
}
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try {
int result = 10 / 0; // This will throw an ArithmeticException
[Link]("Result: " + result); // This line will not be executed
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero");
}
The finally block is always executed, regardless of whether an exception is thrown or caught. It's typically used
to release resources (e.g., close files, database connections).
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to execute if an exception occurs
} finally {
// Code that will always be executed
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
[Link]("Age is valid");
}
Used in a method declaration to indicate that the method might throw a particular exception.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
public void readFile(String filename) throws IOException {
// Code that reads a file (might throw an IOException)
}
Chapter 11: Input and Output Streams
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
[Link]("Hello, " + name + "! You are " + age + " years old.");
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
import [Link];
Swing is a GUI (Graphical User Interface) toolkit for Java. It allows you to create window-based applications
with buttons, labels, text fields, and other interactive components.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link].*;
import [Link].*;
add(label);
add(button);
setVisible(true);
}
Explanation:
Event handling allows you to respond to user interactions, such as button clicks.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link].*;
import [Link].*;
import [Link];
import [Link];
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});
add(button);
add(label);
setVisible(true);
}
public static void main(String[] args) {
[Link](() -> new ButtonClickExample());
}
}
Chapter 13: Working with Collections
The Java Collections Framework provides a set of interfaces and classes for storing and manipulating
collections of objects.
12. List: An ordered collection that allows duplicate elements (e.g., ArrayList, LinkedList).
13. Set: An unordered collection that does not allow duplicate elements (e.g., HashSet, TreeSet).
14. Map: A collection that stores key-value pairs (e.g., HashMap, TreeMap).
13.3 ArrayList
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("Alice"); // Duplicates are allowed
[Link]("Bob");
[Link](names); // Output: [Alice, Charlie, Alice]
13.4 LinkedList
A linked list implementation of the List interface. Efficient for inserting and deleting elements in the middle of
the list.
13.5 HashSet
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("Alice"); // Duplicate is ignored
13.6 HashMap
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 28);
[Link]("Bob");
Multithreading allows a program to execute multiple tasks concurrently. Each task is executed in a separate
thread.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class MyThread extends Thread {
@Override
public void run() {
[Link]("Thread " + [Link]().getName() + " is running");
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class MyRunnable implements Runnable {
@Override
public void run() {
[Link]("Thread " + [Link]().getName() + " is running");
}
When multiple threads access the same shared resources, you need to synchronize them to prevent race
conditions. A race condition occurs when multiple threads try to access and modify shared data concurrently,
leading to unpredictable results.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Counter {
private int count = 0;
Example:
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
class Counter {
private int count = 0;
[Link]();
[Link]();
18. The increment() method is declared as synchronized. This means that only one thread can execute this
method at a time.
19. [Link](); and [Link](); ensure that the main thread waits for thread1 and thread2 to
complete before printing the final count.
20. New: The thread has been created but not yet started.
21. Runnable: The thread is ready to run.
22. Running: The thread is currently executing.
23. Blocked/Waiting: The thread is waiting for a resource or another thread.
24. Terminated: The thread has finished executing.
Chapter 15: Introduction to Java Database Connectivity (JDBC)
JDBC (Java Database Connectivity) is a Java API for connecting to and interacting with databases. It allows you
to execute SQL queries, insert data, update data, and delete data from your Java programs.
25. JDBC Driver: A software component that allows Java applications to connect to a specific database.
26. DriverManager: A class that manages JDBC drivers.
27. Connection: Represents a connection to a database.
28. Statement: Used to execute SQL queries.
29. ResultSet: Represents the result of a query.
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try {
[Link]("[Link]"); // Example for MySQL
} catch (ClassNotFoundException e) {
[Link]("MySQL JDBC Driver not found: " + [Link]());
return;
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
import [Link];
} catch (SQLException e) {
[Link]("Connection failed: " + [Link]());
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
import [Link];
import [Link];
String sql = "CREATE TABLE IF NOT EXISTS students (id INT PRIMARY KEY, name VARCHAR(255))";
[Link](sql); // Executes the SQL statement
[Link]("Table created/verified successfully!");
} catch (SQLException e) {
[Link]("Error executing query: " + [Link]());
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try (Connection connection = [Link](url, username, password);
Statement statement = [Link]()) {
String sql = "INSERT INTO students (id, name) VALUES (1, 'Alice')";
int rowsAffected = [Link](sql);
[Link](rowsAffected + " row(s) inserted.");
} catch (SQLException e) {
[Link]("Error executing query: " + [Link]());
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
[Link]("Error executing query: " + [Link]());
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try (Connection connection = [Link](url, username, password);
Statement statement = [Link]()) {
} catch (SQLException e) {
[Link]("Error executing query: " + [Link]());
}
java<button><svg><path></path></svg><span>Copy code</span><span></span></button>
try (Connection connection = [Link](url, username, password);
Statement statement = [Link]()) {
} catch (SQLException e) {
[Link]("Error executing query: " + [Link]());
}
It's crucial to close database connections, statements, and result sets to release resources. The "try-with-
resources" statement (shown in the examples) automatically closes these resources.
Note: Error Handling should be robust for real applications and not just [Link] statements.
Conclusion:
Java Fundamentals for BCA Students: A Practical Guide, provides a concise and practical introduction to the Java
programming language, specifically designed for students in Bachelor of Computer Applications (BCA) programs. It starts
with fundamental programming concepts and guides readers through setting up their development environment. It
covers core Java elements, including variables, data types, operators, control flow statements (decision-making and
loops), and Object-Oriented Programming (OOP) principles like objects, classes, methods, inheritance, and
polymorphism. Essential data structures like arrays and strings are explained in detail. Furthermore, it introduces
exception handling for robust code, input/output streams for data handling, and a brief overview of GUI programming
with Swing. It also touches upon collections for efficient data management, multithreading basics for concurrent
programming, and an introduction to Java Database Connectivity (JDBC) for database interaction. Due to the length
constraint, it also focuses on the core essentials, providing practical examples and exercises to build a solid foundation
*****************