Original BCA Nepal study material. Units and topic order follow the approved 2025 Tribhuvan University (TU) BCA curriculum outline for BCA153 (OOP in Java). All explanations, code samples, diagrams, and revision questions are original pedagogical material prepared for TU BCA semester students.


Course Overview

Course Code: BCA153
Course Title: OOP in Java
Semester: 2
Credit Hours: 3
Lecture Hours: 3 Hrs/week (Total 48 Lecture Hours)
Evaluation Scheme: Internal Assessment (40%) + Final Board Examination (60%)

Object-Oriented Programming (OOP) in Java introduces students to modern software development using the Java programming language. Java is a versatile, concurrent, class-based, object-oriented language designed to have as few implementation dependencies as possible ("Write Once, Run Anywhere"). The course bridges procedural thinking from C programming (BCA102) to modular, object-oriented architectures, covering classes, encapsulation, inheritance, polymorphism, abstract structures, robust exception handling, multithreading, file streams, generic collections, and modern Java features such as lambdas and streams.


Learning Outcomes Derived from Approved TOC

Upon successful completion of this course, students will be able to:

  1. Explain the fundamental principles of Object-Oriented Programming and distinguish them from procedural paradigms.
  2. Describe Java’s architectural model, including bytecode execution within the JVM, and write, compile, and debug Java console applications.
  3. Apply language fundamentals including primitive types, reference types, arrays (rectangular and jagged), operators, and control flow.
  4. Design robust, reusable classes utilizing encapsulation, access modifiers, constructors, the this reference, and package structures.
  5. Implement polymorphic hierarchies using method overloading, method overriding, abstract classes, interfaces, and the super keyword.
  6. Build fault-tolerant programs using structured exception handling and create concurrent applications using Java multithreading and thread synchronization.
  7. Perform persistent file I/O operations using byte streams, character streams, object serialization, and RandomAccessFile.
  8. Utilize the Java Collections Framework (List, Set, Map) and Generics for type-safe data structuring.
  9. Implement modern software architectural idioms including foundational design patterns (Singleton, Factory, Observer), Lambda expressions, and the Stream API.

Unit 1: Introduction to Java and OOP Concept

Teaching Hours: 4

1.1 History, features or buzzwords of Java

Plain-Language Definition and Origin

Java is a high-level, class-based, object-oriented programming language originally developed by James Gosling and his team ("Green Team") at Sun Microsystems in 1991 (initially called Oak, aimed at smart consumer electronic appliances). It was officially released to the public in 1995 as Java 1.0, targeting the emerging World Wide Web with its promise of architectural neutrality. Sun Microsystems was later acquired by Oracle Corporation in 2010, which continues to maintain and evolve the Java SE (Standard Edition) platform.

The Primary Buzzwords (Features of Java)

The official Java white paper identifies several key features often described as "buzzwords":

  1. Simple: Java syntax is modeled closely on C and C++, making it approachable for programmers. It omits confounding, error-prone constructs such as explicit pointer manipulation, operator overloading, and multiple class inheritance.
  2. Object-Oriented: Everything in Java (except primitive data types) is modeled as objects carrying state and behavior. The language strictly enforces encapsulation, inheritance, and polymorphism.
  3. Platform Independent / Architectural Neutral: Java adheres to the principle of WORA ("Write Once, Run Anywhere"). Java source code (.java) is compiled into intermediate bytecode (.class), which runs on any platform that has a compatible Java Virtual Machine (JVM).
  4. Robust: Java provides compile-time error checking, runtime dynamic type checking, strictly managed memory with automated Garbage Collection (GC), and structured Exception Handling, eliminating wild pointer corruption and memory leaks common in C/C++.
  5. Secure: Java applications run inside a secure runtime sandbox monitored by the Security Manager and Class Loader. Bytecode verification ensures that untrusted network code cannot tamper with host operating system memory.
  6. Distributed: Java natively integrates networking libraries (java.net), Remote Method Invocation (RMI), and web protocols, simplifying distributed client-server applications.
  7. Multithreaded: Java has native language support for concurrent execution, thread synchronization primitives (synchronized, locks), and scheduling, allowing smooth interactive GUIs and high-throughput server backends.
  8. Interpreted and High Performance: Java bytecode is executed by the JVM interpreter, while critical performance-sensitive code is compiled just-in-time (JIT compiler) directly into native machine instructions during execution.
  9. Dynamic: Java programs can dynamically load classes, inspect libraries at runtime via Reflection (java.lang.reflect), and adapt to changing execution environments without recompiling the entire system.
flowchart TD
    A[Java Source Code: Hello.java] -->|javac Compiler| B[Java Bytecode: Hello.class]
    B --> C[Windows JVM]
    B --> D[Linux JVM]
    B --> E[macOS JVM]
    C --> F[Windows Native Instructions]
    D --> G[Linux Native Instructions]
    E --> H[macOS Native Instructions]

Figure 1.1: Platform Independence of Java Bytecode through the JVM.

Exam-Ready Points & Common Mistakes

  • Exam Question Pattern: "Enumerate and explain any five Java buzzwords" or "Explain the concept of platform independence in Java."
  • Common Mistake: Confusing "platform independence" with "JVM independence." Java bytecode is platform-independent, but the JVM itself is platform-dependent (there are distinct JVM implementations for Windows, Linux, and macOS).

1.2 Java architecture: JVM, JDK and JRE

Core Architecture Definitions

To understand how Java works, students must clearly differentiate between JDK, JRE, and JVM:

  1. JVM (Java Virtual Machine): An abstract computing machine that provides the runtime execution environment for Java bytecode. It manages CPU registers, stack, heap, garbage collection, and native method interfaces.
  2. JRE (Java Runtime Environment): The software package required to run compiled Java programs. It bundles the JVM along with the core Java Class Libraries (e.g., java.lang, java.util, java.io).
  3. JDK (Java Development Kit): The comprehensive software package required to develop and execute Java applications. It contains the JRE, the compiler (javac), archiver (jar), debugger (jdb), and documentation generator (javadoc).
flowchart TD
    subgraph JDK [Java Development Kit - JDK]
        subgraph JRE [Java Runtime Environment - JRE]
            subgraph JVM [Java Virtual Machine - JVM]
                CL[Class Loader Subsystem]
                MA[Method Area & Heap]
                EE[Execution Engine: Interpreter + JIT + GC]
            end
            CoreLib[Core Java Class Libraries: rt.jar, java.base]
        end
        DevTools[Development Tools: javac, java, jar, javadoc, jdb]
    end

Figure 1.2: Structural Relationship between JDK, JRE, and JVM.

Internal Subsystems of JVM

  • Class Loader Subsystem: Responsible for loading (.class files), linking (verifying bytecode safety, preparing static variables, resolving symbolic references), and initializing static blocks.
  • JVM Memory Areas:
    • Method Area (Metaspace): Stores class-level data, bytecode, static variables, and method metadata.
    • Heap Area: Holds all instantiated objects and instance variables; monitored by Garbage Collection.
    • Java Stack: Stores stack frames for method invocation, local variables, and intermediate calculation results.
    • PC Registers: Holds the memory address of the JVM instruction currently being executed for each active thread.
    • Native Method Stack: Houses native C/C++ function calls executed via JNI (Java Native Interface).
  • Execution Engine: Executes bytecode via:
    • Interpreter: Reads and executes bytecode instructions one by one.
    • JIT (Just-In-Time) Compiler: Analyzes hot spots (frequently executed loops/methods) and compiles them into direct hardware machine code for rapid execution.
    • Garbage Collector (GC): Automatically reclaims unreferenced heap memory.

Comparison Table: JDK vs. JRE vs. JVM

Feature JDK JRE JVM
Full Form Java Development Kit Java Runtime Environment Java Virtual Machine
Primary Purpose Developing, compiling, and running Java programs Running already compiled Java applications Executing bytecode instructions on hardware
Target Audience Software developers and students End-users running Java software Internal execution engine (runtime layer)
Contains Tools javac, jar, javadoc, debugger + JRE JVM + core Java class libraries (rt.jar) Class loader, execution engine (JIT + interpreter), GC
Platform Nature Platform-dependent Platform-dependent Platform-dependent

Swipe to see all columns


1.3 Procedural-oriented vs. object-oriented programming

Conceptual Foundations

  • Procedural-Oriented Programming (POP): Focuses on procedures, routines, or functions. The primary goal is step-by-step task execution. Data moves freely across functions as global variables or function parameters, resulting in high coupling and fragile security (e.g., standard C).
  • Object-Oriented Programming (OOP): Focuses on objects combining both data (attributes) and behavior (methods). Programs are organized into interacting entities. Data is protected through encapsulation, and access is strictly regulated through defined interfaces.

Explicit Comparison Table

Aspect Procedural-Oriented (e.g., C) Object-Oriented (e.g., Java)
Core Entity Functions / Procedures Objects and Classes
Approach Top-down design Bottom-up design
Data Security Weak; data moves freely between functions Strong; data hiding through access specifiers (private)
Code Reusability Limited; manual function copying and linking High; supported natively via Inheritance and Composition
Polymorphism Not natively supported Supported via method overloading and overriding
Memory Allocation Explicit manual allocation (malloc/free) Automatic via new operator and garbage collection
Maintenance Complex for large systems Modular and straightforward to refactor

1.4 Setting up Java environment and IDE in local machine

Setup Steps on Windows/Linux/macOS

  1. Download and Install OpenJDK / Oracle JDK: Download JDK 17 LTS or JDK 21 LTS from official sources (e.g., Adoptium Temurin or Oracle).
  2. Configuring Environment Variables:
    • Set JAVA_HOME pointing to the JDK installation directory (e.g., C:\Program Files\Eclipse Adoptium\jdk-17.0.x-hotspot\ or /usr/lib/jvm/java-17-openjdk).
    • Append %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Linux/macOS) to the system PATH variable.
  3. Verifying Installation: Open terminal/command prompt and verify:
    javac -version
    java -version
    
  4. Integrated Development Environments (IDEs): While basic programs can be written in text editors (VS Code, Notepad++), standard professional IDEs include IntelliJ IDEA, Eclipse, and Apache NetBeans. IDEs provide automatic syntax highlighting, real-time error checking, refactoring tools, and integrated debugging.

1.5 Sample Java programs

Let us write, analyze, and dissect a complete, runnable Java console program:

// File: WelcomeBCA.java
public class WelcomeBCA {
    public static void main(String[] args) {
        // Output greeting message to standard console
        System.out.println("Welcome to BCA Second Semester OOP in Java!");
    }
}

Line-by-Line Breakdown:

  • public class WelcomeBCA: Defines a class named WelcomeBCA. In Java, all code must reside within a class. The public specifier means this class is accessible from any package. The file name must strictly match the public class name (WelcomeBCA.java).
  • public static void main(String[] args): The standard entry point method called by the JVM:
    • public: Accessible from anywhere, including outside the package by the JVM.
    • static: Can be invoked without creating an instance of the WelcomeBCA class.
    • void: Returns no value to the operating system upon termination.
    • main: The designated entry-point identifier recognized by the JVM.
    • String[] args: An array of String elements holding command-line arguments.
  • System.out.println(...):
    • System: A final class from java.lang providing system-level resources.
    • out: A static instance of PrintStream representing standard output.
    • println: A method that prints the given string followed by a platform-specific newline.

1.6 Compiling and running Java programs

Terminal Commands Workflow

# Step 1: Compile source code into bytecode
javac WelcomeBCA.java

# Step 2: Verify generated bytecode file
# This produces WelcomeBCA.class

# Step 3: Launch Java Virtual Machine to execute bytecode
java WelcomeBCA

Compilation & Execution Mechanics

  1. When javac WelcomeBCA.java is executed, the compiler checks syntax, verifies type safety, resolves imports, and converts source code into portable bytecode instructions stored in WelcomeBCA.class.
  2. When java WelcomeBCA is executed, the OS starts the JVM process. The ClassLoader loads WelcomeBCA.class, the Bytecode Verifier checks security constraints, and the Execution Engine invokes the main method.

1.7 Command-line arguments

Definition and Purpose

Command-line arguments allow users to pass parameters to the Java application at the time of program launch through the console. These arguments are captured as an array of String objects in the parameter args of the main(String[] args) method.

Worked Example: Summing Command-Line Arguments

// File: CmdArgsDemo.java
public class CmdArgsDemo {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Error: Please provide at least two integer numbers.");
            System.out.println("Usage: java CmdArgsDemo <num1> <num2>");
            return;
        }

        int sum = 0;
        System.out.println("Total arguments received: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + i + ": " + args[i]);
            // Convert string token to integer
            sum += Integer.parseInt(args[i]);
        }
        System.out.println("Calculated Total Sum = " + sum);
    }
}

Execution and Output Trace

javac CmdArgsDemo.java
java CmdArgsDemo 15 25 60

Output:

Total arguments received: 3
Argument 0: 15
Argument 1: 25
Argument 2: 60
Calculated Total Sum = 100

Common Pitfall: Accessing args[0] without checking args.length throws ArrayIndexOutOfBoundsException if no arguments are supplied.


1.8 Scanner class for input

Definition and Usage

The java.util.Scanner class is a versatile utility used to parse primitive data types and strings from input streams (such as System.in) using regular expressions and delimiter tokens.

Complete Worked Example

// File: StudentInputDemo.java
import java.util.Scanner;

public class StudentInputDemo {
    public static void main(String[] args) {
        // Instantiate Scanner wrapping standard input stream
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter Student Full Name: ");
        String name = scanner.nextLine(); // Reads full line including spaces

        System.out.print("Enter Roll Number: ");
        int rollNumber = scanner.nextInt();

        System.out.print("Enter Semester GPA: ");
        double gpa = scanner.nextDouble();

        System.out.println("\n--- Student Academic Profile ---");
        System.out.println("Name        : " + name);
        System.out.println("Roll Number : " + rollNumber);
        System.out.println("GPA         : " + gpa);

        // Good practice: close scanner to release underlying stream
        scanner.close();
    }
}

The nextLine() Trap

When invoking nextInt() or nextDouble(), the numeric scanner method reads only the number token, leaving the trailing newline character \n in the buffer. If a subsequent nextLine() is called immediately after, it consumes the lingering newline and appears to skip user input.
Remedy: Place a dummy scanner.nextLine(); immediately after reading numbers before reading strings.


1.9 Handling common errors

In Java programming, errors are broadly classified into three categories:

  1. Compile-time Errors (Syntax/Semantic Errors): Detected by javac. Examples:
    • Missing semicolon (;), mismatched braces {}.
    • Type mismatch (e.g., int x = "Hello";).
    • Using uninitialized local variables.
  2. Run-time Errors (Exceptions): Occur during program execution when an illegal operation is attempted. Examples:
    • ArithmeticException: Division by integer zero (10 / 0).
    • NullPointerException: Invoking a method on an object reference that is null.
    • ArrayIndexOutOfBoundsException: Index outside the bounds [0, length - 1].
  3. Logical Errors (Bugs): Program compiles and runs without crashing, but yields incorrect outputs due to algorithmic faults (e.g., using + instead of * in interest formulas).

Debugging Strategies

  • Read compiler diagnostic messages carefully: they provide the file name, line number, and error token.
  • Use structured exception handling (try-catch) for predictable runtime conditions.
  • Employ interactive IDE debuggers with breakpoints and variable inspection.

Unit 2: Basics of Java Programming

Teaching Hours: 8

2.1 Writing comments and its types

Comments are non-executable explanatory notes written in the source code to improve readability and maintainability. In Java, there are three distinct comment types:

  1. Single-Line Comments: Begins with // and extends to the end of the line.
    // Calculate net salary after tax deduction
    double netSalary = grossSalary - tax;
    
  2. Multi-Line Comments: Enclosed between /* and */. Used for descriptive explanations spanning multiple lines. Cannot be nested.
    /*
     * This algorithm sorts an array of integers
     * using the standard bubble sort technique.
     */
    
  3. Documentation Comments (Javadoc): Enclosed between /** and */. Extracted by the javadoc tool to generate standardized HTML API documentation. Supports special tags such as @param, @return, and @throws.
    /**
     * Computes compound interest.
     * @param principal Initial invested amount in NPR.
     * @param rate Annual interest rate percentage.
     * @param years Investment term in years.
     * @return Total maturity amount.
     */
    public double calculateMaturity(double principal, double rate, int years) {
        return principal * Math.pow(1 + rate / 100.0, years);
    }
    

2.2 Java tokens: keywords, identifiers, literals, operators and separators

A token is the smallest individual building block recognized by the Java compiler.

  1. Keywords: Reserved words with predefined meanings in Java syntax (e.g., class, public, static, void, int, if, while, return, extends, implements, super, this). Keywords cannot be used as variable or class names.
  2. Identifiers: Names assigned by programmers to classes, methods, variables, and packages.
    • Rules: Must begin with a letter (A-Z, a-z), underscore (_), or dollar sign ($). Cannot begin with a digit. Cannot be a keyword. Case-sensitive (totalMarks != TotalMarks).
  3. Literals: Constant values assigned directly to variables:
    • Integer literals: 100, 0x1F (hexadecimal), 0b1010 (binary).
    • Floating-point literals: 3.14159f (float), 2.71828 (double).
    • Character literals: 'A', '\n', '\u0041'.
    • String literals: "Kathmandu, Nepal".
    • Boolean literals: true, false.
    • Null literal: null.
  4. Separators (Punctuators): Organize code structure: parentheses (), braces {}, brackets [], semicolon ;, comma ,, and period ..
  5. Operators: Symbols specifying data manipulation:
    • Arithmetic: +, -, *, /, %
    • Relational: ==, !=, <, >, <=, >=
    • Logical: &&, ||, !
    • Bitwise: &, |, ^, ~, <<, >>, >>>
    • Assignment: =, +=, -=, *=, /=, %=
    • Ternary: condition ? expr1 : expr2

2.3 Data types: primitive and user-defined data types

Java is a strongly typed language, requiring explicit declaration of types for all variables.

flowchart TD
    DT[Java Data Types] --> P[Primitive Types - 8 Built-in]
    DT --> R[Reference / User-Defined Types]
    P --> Num[Numeric]
    P --> Char[Character: char 16-bit Unicode]
    P --> Bool[Boolean: boolean true/false]
    Num --> Int[Integral: byte, short, int, long]
    Num --> Float[Floating Point: float, double]
    R --> Cls[Classes]
    R --> Intf[Interfaces]
    R --> Arr[Arrays]
    R --> Enm[Enums]

Figure 2.1: Classification of Java Data Types.

The 8 Primitive Data Types

Type Size Default Value Range
byte 1 byte (8 bits) 0 -128 to 127
short 2 bytes (16 bits) 0 -32,768 to 32,767
int 4 bytes (32 bits) 0 -2^31 to 2^31 - 1
long 8 bytes (64 bits) 0L -2^63 to 2^63 - 1
float 4 bytes (32 bits) 0.0f ±1.4E-45 to ±3.4E+38
double 8 bytes (64 bits) 0.0d ±4.9E-324 to ±1.7E+308
char 2 bytes (16 bits) '\u0000' 0 to 65,535 (Unicode)
boolean 1 bit (JVM dependent) false true or false

Swipe to see all columns

User-defined/Reference Types: Hold references (memory addresses) to dynamically allocated objects in the heap.


2.4 Variable declaration and assignment, expressions

Variable Declaration Syntax

dataType variableName [= initialValue];
  • Variables can be classified into:
    1. Local Variables: Declared inside methods/blocks. Must be explicitly initialized before use.
    2. Instance Variables: Declared inside class, outside methods. Initialized automatically with default values.
    3. Static (Class) Variables: Declared with static keyword. Shared across all instances of the class.

Expressions

An expression is an evaluable combination of variables, constants, method calls, and operators yielding a value:

int a = 10, b = 20, c = 5;
// Expression evaluation adhering to operator precedence (* before +)
double result = a + b * (double) c / 2; // 10 + 20 * 5.0 / 2 = 10 + 50.0 = 60.0

2.5 Control statements: selection statements, looping statements and jump statements

Control statements regulate the execution flow based on logical criteria.

1. Selection Statements

  • if, if-else, and nested if-else-if ladders.
  • switch statement: selects one branch among multiple execution paths based on an integral, character, enum, or String expression:
switch (dayOfWeek) {
    case 1: System.out.println("Sunday"); break;
    case 2: System.out.println("Monday"); break;
    // ...
    default: System.out.println("Invalid Day"); break;
}

2. Looping Statements

  • while: Entry-controlled loop; checks condition before executing body.
  • do-while: Exit-controlled loop; guarantees at least one execution.
  • for: Count-controlled loop combining initialization, condition, and update.
  • Enhanced for-each: Traverses arrays and collections sequentially.

3. Jump Statements

  • break: Immediately terminates the innermost loop or switch.
  • continue: Skips remainder of current iteration and proceeds to next loop test.
  • return: Returns execution control (and optional value) from current method.

2.6 Arrays: single dimension array, multi-dimensional array (rectangular and jagged)

An array in Java is a dynamically created object that stores a fixed-size sequential collection of elements of the same data type.

Single-Dimensional Array

// Declaration, allocation, and initialization
int[] numbers = new int[5]; // Allocated on heap, default 0s
numbers[0] = 10;
numbers[1] = 20;

int[] primes = {2, 3, 5, 7, 11}; // Array literal

Rectangular vs. Jagged Multi-Dimensional Arrays

  • Rectangular Array: All rows have the same number of columns.
  • Jagged (Ragged) Array: An array of arrays where each row can have a different length.
// File: JaggedArrayDemo.java
public class JaggedArrayDemo {
    public static void main(String[] args) {
        // Declare a jagged 2D array with 3 rows
        int[][] jagged = new int[3][];
        jagged[0] = new int[2]; // Row 0 has 2 columns
        jagged[1] = new int[4]; // Row 1 has 4 columns
        jagged[2] = new int[3]; // Row 2 has 3 columns

        // Populate jagged array
        int count = 1;
        for (int i = 0; i < jagged.length; i++) {
            for (int j = 0; j < jagged[i].length; j++) {
                jagged[i][j] = count++;
            }
        }

        // Print jagged array
        System.out.println("Jagged Array Structure:");
        for (int i = 0; i < jagged.length; i++) {
            for (int val : jagged[i]) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

Output:

Jagged Array Structure:
1 2 
3 4 5 6 
7 8 9 

2.7 Type conversion and casting

Type conversion involves converting a value of one data type into another.

  1. Implicit Type Casting (Widening Conversion):
    Occurs automatically when converting a smaller data type to a larger data type without risk of data loss:
    byte → short → int → long → float → double.

    int myInt = 100;
    double myDouble = myInt; // Automatic widening: 100.0
    
  2. Explicit Type Casting (Narrowing Conversion):
    Required when assigning a larger data type to a smaller data type; requires explicit cast operator (type). Risk of precision loss or overflow:

    double pi = 3.14159;
    int approxPi = (int) pi; // Explicit narrowing: truncates decimals to 3
    
    int largeNum = 130;
    byte byteVal = (byte) largeNum; // Overflow: 130 wraps around to -126 in 8-bit two's complement
    

2.8 Garbage collection

Concept and Mechanism

In C/C++, developers must manually free dynamically allocated memory (free() or delete), causing dangling pointers and memory leaks. Java solves this via Garbage Collection (GC): an autonomous background daemon thread in the JVM that identifies and reclaims heap memory occupied by objects that are no longer reachable by any active thread.

Reclaiming Objects

An object becomes eligible for garbage collection when:

  1. Its reference is set to null (obj = null;).
  2. Its reference is reassigned to another object (obj1 = obj2;).
  3. It was created inside a method that has finished execution (out of scope).
  4. It belongs to an isolated island of references disconnected from root references.

Requesting GC

System.gc(); // Suggests JVM perform GC; execution is not guaranteed immediately

2.9 Strings: creation, concatenation, comparison, modification, changing case and searching

In Java, String is an immutable class in java.lang. Once created, its internal character array cannot be modified.

String Creation: String Constant Pool vs. Heap

String s1 = "Nepal";               // Stored in String Constant Pool (SCP)
String s2 = "Nepal";               // Reuses same instance from SCP (s1 == s2 is true)
String s3 = new String("Nepal");   // Explicitly allocated on Heap outside SCP (s1 == s3 is false)

Core String Operations

// File: StringOperationsDemo.java
public class StringOperationsDemo {
    public static void main(String[] args) {
        String greeting = "Hello, ";
        String country = "Nepal!";

        // 1. Concatenation
        String message = greeting.concat(country); // "Hello, Nepal!"

        // 2. Comparison
        boolean equalsLiteral = message.equals("Hello, Nepal!"); // true (compares contents)
        boolean equalsIgnoreCase = message.equalsIgnoreCase("hello, nepal!"); // true

        // 3. Modification (returns new String instance due to immutability)
        String replaced = message.replace("Nepal", "World"); // "Hello, World!"

        // 4. Case transformation
        String upper = message.toUpperCase(); // "HELLO, NEPAL!"
        String lower = message.toLowerCase(); // "hello, nepal!"

        // 5. Searching
        int index = message.indexOf("Nepal"); // 7
        boolean containsWord = message.contains("Hello"); // true

        System.out.println("Final Message: " + message);
        System.out.println("Upper Case: " + upper);
        System.out.println("Found 'Nepal' at index: " + index);
    }
}

2.10 StringBuffer class

Immutability vs. Mutability

Because String is immutable, frequent concatenation in loops creates numerous discarded temporary string objects in memory. StringBuffer is a mutable, thread-safe peer class that allows modifications in place.

Key Methods of StringBuffer

  • append(data): Appends data to sequence.
  • insert(offset, data): Inserts data at designated index.
  • replace(start, end, str): Replaces substring range.
  • delete(start, end): Removes characters in range.
  • reverse(): Reverses the character sequence.
// File: StringBufferDemo.java
public class StringBufferDemo {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Tribhuvan");
        sb.append(" University");
        System.out.println("Appended: " + sb);

        sb.insert(9, " Institute &");
        System.out.println("Inserted: " + sb);

        sb.reverse();
        System.out.println("Reversed: " + sb);
    }
}
Property String StringBuffer StringBuilder
Mutability Immutable Mutable Mutable
Thread Safety Thread-safe (read-only) Thread-safe (synchronized) Not thread-safe
Performance Slow on repeated modification Moderate Fastest (single thread)

Swipe to see all columns


Unit 3: Classes and Objects in Java

Teaching Hours: 8

3.1 Defining class, adding method to class, creating object and calling function/method

Concepts

  • Class: A user-defined blueprint or prototype from which objects are created. It encapsulates field variables (state) and methods (behavior).
  • Object: A concrete instance of a class occupying physical memory in the heap.
// File: AccountDemo.java
class BankAccount {
    // Instance variables (State)
    private String accountNumber;
    private double balance;

    // Method to initialize
    public void initialize(String accNo, double initialBalance) {
        accountNumber = accNo;
        balance = initialBalance;
    }

    // Method (Behavior) to deposit money
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited NPR " + amount + ". New Balance: " + balance);
        }
    }

    // Method to display account status
    public void displayStatus() {
        System.out.println("Account: " + accountNumber + " | Balance: NPR " + balance);
    }
}

public class AccountDemo {
    public static void main(String[] args) {
        // Object instantiation using 'new' operator
        BankAccount myAcc = new BankAccount();
        // Method calls
        myAcc.initialize("BCA-2025-001", 5000.0);
        myAcc.deposit(2500.0);
        myAcc.displayStatus();
    }
}

3.2 Abstraction and encapsulation

  • Encapsulation: The practice of binding data (fields) and the methods that operate on that data into a single protective capsule (class), while restricting direct external access to internal representation. Achieved by declaring variables private and exposing public accessor (getter) and mutator (setter) methods.
  • Abstraction: The mechanism of exposing essential functional features while concealing complex underlying implementation details. Achieved via abstract classes and interfaces.
classDiagram
    class Student {
        -int rollNumber
        -String name
        -double marks
        +getRollNumber() int
        +getName() String
        +setName(String name) void
        +setMarks(double marks) void
        +calculateGrade() char
    }

Figure 3.1: Encapsulation with Private State and Controlled Public Accessors.


3.3 Constructors and its types (default, parameterized and copy)

A constructor is a special member block invoked automatically when an object is instantiated via new. It shares the exact name of the class and has no return type (not even void).

  1. Default (No-Arg) Constructor: Automatically provided by the compiler if no constructors are declared; initializes fields to default zero/null values.
  2. Parameterized Constructor: Accepts arguments to initialize instance variables with custom values during creation.
  3. Copy Constructor: Creates an identical object by copying values from an existing object of the same class.
// File: RectangleDemo.java
class Rectangle {
    private double length;
    private double breadth;

    // 1. Default constructor
    public Rectangle() {
        this.length = 1.0;
        this.breadth = 1.0;
    }

    // 2. Parameterized constructor
    public Rectangle(double length, double breadth) {
        this.length = length;
        this.breadth = breadth;
    }

    // 3. Copy constructor
    public Rectangle(Rectangle other) {
        this.length = other.length;
        this.breadth = other.breadth;
    }

    public double getArea() {
        return length * breadth;
    }
}

3.4 'this' keyword

The this keyword is a reference variable that points directly to the current invoking object instance.

Major Usages:

  1. Disambiguate instance variables from method/constructor parameters:
    public void setDimensions(double length, double breadth) {
        this.length = length; // 'this.length' refers to field; 'length' refers to parameter
        this.breadth = breadth;
    }
    
  2. Constructor Chaining (this()): Invokes another constructor within the same class (must be the first statement).
    public Rectangle(double side) {
        this(side, side); // Delegates to two-argument constructor
    }
    
  3. Passing current object as argument: displayInfo(this);.

3.5 Static fields and methods

The static modifier signifies that a member belongs to the class itself, rather than to any individual object instance.

  • Static Variable: Only one copy exists in memory, shared by all instances. Ideal for constants or counters.
  • Static Method: Can be invoked directly using class name without creating objects (ClassName.method()). Cannot access non-static instance fields or call this directly.
  • Static Block: Executed once when the class is loaded into memory by the ClassLoader.
// File: StaticDemo.java
class CollegeStudent {
    private String name;
    private static String collegeName = "TU BCA Department"; // Shared static field
    private static int studentCount = 0;

    public CollegeStudent(String name) {
        this.name = name;
        studentCount++; // Increment shared counter
    }

    public static int getTotalStudents() {
        return studentCount; // Static method accessing static field
    }
}

3.6 Method passing: passing by value, by reference

Crucial Java Rule: Java is strictly pass-by-value at all times.

  • When passing primitive types, a copy of the actual value is passed. Modifications made inside the method do not affect the caller's original variable.
  • When passing object references, a copy of the reference address is passed by value. Both caller and callee reference the exact same underlying heap object. Mutating object fields modifies the original object; however, reassigning the reference variable itself inside the method does not rebind the caller's original reference.
// File: PassByValueProof.java
class Counter {
    int value = 10;
}

public class PassByValueProof {
    public static void modify(int num, Counter c) {
        num = 99;         // Primitive: only local copy changes
        c.value = 500;    // Reference contents modified: affects heap object
        c = new Counter();// Reassigning local reference: does NOT reassign caller's object
    }

    public static void main(String[] args) {
        int x = 5;
        Counter myCounter = new Counter();
        modify(x, myCounter);
        System.out.println("x = " + x);                    // Still 5
        System.out.println("Counter = " + myCounter.value);// Changed to 500
    }
}

3.7 Recursion

Recursion is a programming technique where a method calls itself to solve a smaller subproblem of the original task. Every recursive method must contain:

  1. Base Case: Terminating condition that returns without further self-calls, preventing infinite call stack growth (StackOverflowError).
  2. Recursive Step: Operation reducing the problem size towards the base condition.

Worked Example: Factorial with Trace

public class RecursionDemo {
    public static long factorial(int n) {
        if (n <= 1) { // Base case
            return 1;
        }
        return n * factorial(n - 1); // Recursive call
    }
}

Stack Trace for factorial(3):

  1. factorial(3) pushes stack frame, calls 3 * factorial(2).
  2. factorial(2) pushes stack frame, calls 2 * factorial(1).
  3. factorial(1) hits base case, returns 1.
  4. Stack unwinds: 2 * 1 = 2, then 3 * 2 = 6.

3.8 Nested and inner class

In Java, classes can be defined within other classes.

  1. Member Inner Class: Non-static class defined inside an outer class. Has direct access to all outer class members (including private ones). Requires an instance of the outer class to be created.
    Outer out = new Outer();
    Outer.Inner in = out.new Inner();
    
  2. Static Nested Class: Defined with the static keyword. Can be instantiated without an outer class instance. Cannot access non-static outer members directly.
    Outer.StaticNested nested = new Outer.StaticNested();
    
  3. Local Inner Class: Defined inside a method block; visible only within that method.
  4. Anonymous Inner Class: Class without a name, declared and instantiated simultaneously for short callbacks or event listeners.

3.9 Variable length arguments (Varargs)

Introduced to allow methods to accept zero or more arguments of a specified type without requiring manual array creation.

Syntax Rule:

The varargs ellipsis ... must be the last parameter in the method signature, and only one varargs parameter is permitted per method.

// File: VarargsDemo.java
public class VarargsDemo {
    public static double average(double... values) {
        if (values.length == 0) return 0.0;
        double sum = 0.0;
        for (double v : values) {
            sum += v;
        }
        return sum / values.length;
    }

    public static void main(String[] args) {
        System.out.println("Avg 2 nums: " + average(10.5, 20.5));
        System.out.println("Avg 4 nums: " + average(5, 10, 15, 20));
    }
}

3.10 Packages: defining and importing packages

A package is a grouped namespace container that organizes related classes and interfaces, prevents name collisions, and controls access levels.

Defining a Package

The package statement must be the first line of code in the source file:

package np.edu.tu.bca;

public class CourseInfo {
    public void printDetails() {
        System.out.println("TU BCA Syllabus 2025");
    }
}

Directory Structure: The file must reside in np/edu/tu/bca/CourseInfo.java.

Importing a Package

import np.edu.tu.bca.CourseInfo; // Specific import
import java.util.*;              // Wildcard import (imports all classes in java.util)

Unit 4: Inheritance and Polymorphism

Teaching Hours: 6

4.1 Inheritance basics

Inheritance is the mechanism by which a new class (subclass or derived class) acquires the fields and methods of an existing class (superclass or base class) using the extends keyword. It promotes code reusability and establishes an "IS-A" relationship.

classDiagram
    class Person {
        #String name
        #int age
        +displayBio() void
    }
    Person <|-- Student
    class Student {
        -String rollNo
        +study() void
    }

Figure 4.1: Inheritance establishing an "IS-A" relationship.


4.2 Inheritance types (single-level, multi-level, multiple and hierarchical)

  1. Single-Level Inheritance: One subclass inherits from one superclass ($A ightarrow B$).
  2. Multi-Level Inheritance: A class inherits from a subclass, forming an inheritance chain ($A ightarrow B ightarrow C$).
  3. Hierarchical Inheritance: Multiple subclasses inherit from a single common superclass ($A ightarrow B$ and $A ightarrow C$).
  4. Multiple Inheritance: A class inherits directly from more than one superclass. Java does not support multiple inheritance with classes to prevent ambiguity ("Diamond Problem"). However, Java achieves multiple inheritance through Interfaces.

4.3 'super' keyword

The super keyword is a reference variable used to refer directly to the immediate parent superclass.

Major Usages:

  1. Invoking Superclass Constructor: Must be the first statement in the subclass constructor (super(args);).
  2. Accessing Hidden Superclass Field: super.variableName.
  3. Invoking Overridden Superclass Method: super.methodName().
// File: SuperDemo.java
class Vehicle {
    protected int speed = 60;
    public Vehicle(int speed) {
        this.speed = speed;
    }
    public void display() {
        System.out.println("Vehicle Speed: " + speed);
    }
}

class Car extends Vehicle {
    private int speed = 120; // Hides superclass field

    public Car(int vehicleSpeed, int carSpeed) {
        super(vehicleSpeed); // Invokes Vehicle constructor
        this.speed = carSpeed;
    }

    @Override
    public void display() {
        super.display(); // Calls parent method
        System.out.println("Car Speed: " + speed + " | Base Speed: " + super.speed);
    }
}

4.4 Polymorphism: method overloading and method overriding

Polymorphism ("many forms") allows entities to exhibit different behaviors depending on context.

flowchart TD
    Poly[Polymorphism in Java] --> CompileTime[Compile-Time / Static Polymorphism]
    Poly --> RunTime[Run-Time / Dynamic Polymorphism]
    CompileTime --> Overloading[Method Overloading]
    RunTime --> Overriding[Method Overriding via Dynamic Method Dispatch]

Figure 4.2: Classification of Polymorphism in Java.

Comparison: Overloading vs. Overriding

Parameter Method Overloading Method Overriding
Binding Time Compile-time (Static binding) Run-time (Dynamic method dispatch)
Location Within the same class Between Superclass and Subclass
Method Name Must be identical Must be identical
Argument List Must differ (number, types, or order) Must be identical
Return Type Can be different Must be same or covariant
Private/Static Can overload static and private methods Cannot override static or private methods

Dynamic Method Dispatch Worked Example

// File: DynamicDispatchDemo.java
class Shape {
    void draw() { System.out.println("Drawing generic shape"); }
}
class Circle extends Shape {
    @Override
    void draw() { System.out.println("Drawing a circle"); }
}
class Triangle extends Shape {
    @Override
    void draw() { System.out.println("Drawing a triangle"); }
}

public class DynamicDispatchDemo {
    public static void main(String[] args) {
        Shape s; // Superclass reference variable
        s = new Circle();
        s.draw(); // Dispatches to Circle's draw() at runtime

        s = new Triangle();
        s.draw(); // Dispatches to Triangle's draw() at runtime
    }
}

4.5 Object class

The java.lang.Object class sits at the absolute root of the entire Java class hierarchy. Every class in Java implicitly or explicitly inherits from Object.

Essential Methods to Know for Exams:

  • toString(): Returns a textual representation of the object (default: ClassName@HexHashCode). Should be overridden to provide readable output.
  • equals(Object obj): Compares references for equality (==). Can be overridden to compare deep contents (state).
  • hashCode(): Returns an integer hash value; contract dictates that if a.equals(b) is true, their hashCode() must match.
  • getClass(): Returns the runtime class object.
  • clone(): Creates a field-by-field copy (requires implementing Cloneable).
  • finalize(): Deprecated cleanup hook prior to garbage collection.

4.6 'final' keyword

The final keyword represents restriction and immutability:

  1. Final Variable: Acts as a constant; once assigned, its value cannot be altered.
  2. Final Method: Cannot be overridden by any subclass, preventing altered behavior.
  3. Final Class: Cannot be inherited (cannot extend final class), preventing subclassing (e.g., java.lang.String is final for security).

4.7 Abstract classes and methods

  • Abstract Method: Declared with abstract keyword without an implementation body ({}). Subclasses are forced to provide concrete implementation.
  • Abstract Class: Declared with abstract. Cannot be instantiated directly using new. Can contain both abstract methods and concrete implementations, instance variables, constructors, and static methods.
abstract class Bank {
    // Abstract method: subclasses must define rate
    abstract double getInterestRate();

    // Concrete method common to all banks
    public void displayRegulationNotice() {
        System.out.println("Regulated by Nepal Rastra Bank");
    }
}

4.8 Access control (private, protected, default and public)

Java offers four levels of visibility to enforce data security and encapsulation:

Access Specifier Same Class Same Package Subclass (Other Pkg) Global (Everywhere)
private Yes No No No
default (no keyword) Yes Yes No No
protected Yes Yes Yes (via inheritance) No
public Yes Yes Yes Yes

Swipe to see all columns


4.9 Interfaces: defining, implementing and applying interfaces

An interface is a formal contract specifying what a class must do, but not how it does it. Prior to Java 8, interfaces contained exclusively public static final constants and public abstract methods. (Java 8+ allows default and static methods; Java 9 allows private methods).

Achieving Multiple Inheritance via Interfaces

// File: InterfaceDemo.java
interface Printable {
    void print();
}

interface Showable {
    void show();
}

// Class implementing multiple interfaces
class DocumentReport implements Printable, Showable {
    @Override
    public void print() {
        System.out.println("Printing document report to paper...");
    }

    @Override
    public void show() {
        System.out.println("Rendering document on screen display...");
    }
}

Unit 5: Exception Handling and Multithreading

Teaching Hours: 6

5.1 Basic exceptions, proper use of exceptions

An exception is an abnormal condition or event that disrupts the normal execution flow during runtime. Proper exception handling separates error-handling logic from primary business logic, ensuring graceful degradation rather than abrupt program termination.


5.2 Exception hierarchy

All exception and error types stem from the root class java.lang.Throwable.

flowchart TD
    Throwable[java.lang.Throwable] --> Error[Error - Fatal System Issues]
    Throwable --> Exception[Exception - Application Handled]
    Error --> StackOverflow[StackOverflowError]
    Error --> OutOfMemory[OutOfMemoryError]
    Exception --> RuntimeException[Unchecked: RuntimeException]
    Exception --> CheckedException[Checked: IOException, SQLException, ClassNotFoundException]
    RuntimeException --> Arithmetic[ArithmeticException]
    RuntimeException --> NullPointer[NullPointerException]
    RuntimeException --> ArrayIndex[ArrayIndexOutOfBoundsException]

Figure 5.1: The Java Throwable Exception Hierarchy.

  • Checked Exceptions: Inherit directly from Exception (excluding RuntimeException). Checked at compile-time; compiler forces developer to handle them via try-catch or declare them with throws (e.g., IOException).
  • Unchecked Exceptions: Inherit from RuntimeException. Occur due to programming flaws; compiler does not force explicit handling (e.g., NullPointerException).

5.3 Exception handling keywords: try, catch, throw, throws and finally

  1. try: Encloses code block that may generate exceptions.
  2. catch: Catches and handles specific exception instances. Multiple catch blocks can follow a single try (subclass exception must precede superclass).
  3. finally: Block that always executes, regardless of whether an exception occurred or was handled. Used for guaranteed resource cleanup (closing DB connections, file streams).
  4. throw: Explicitly triggers an exception instance from code (throw new ArithmeticException("Invalid");).
  5. throws: Placed in method declaration to declare exceptions propagated to caller.
// File: TryCatchFinallyDemo.java
import java.io.FileInputStream;
import java.io.IOException;

public class TryCatchFinallyDemo {
    public static void readFile(String path) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            int data = fis.read();
            System.out.println("Read byte: " + data);
        } catch (IOException e) {
            System.err.println("File I/O Error: " + e.getMessage());
            throw e; // Re-throwing exception
        } finally {
            System.out.println("Executing finally block for cleanup...");
            if (fis != null) fis.close();
        }
    }
}

5.4 Java's built-in exceptions

  • ArithmeticException: Erroneous arithmetic operations like division by zero.
  • ArrayIndexOutOfBoundsException: Index out of array bounds.
  • NullPointerException: Accessing members on a null reference.
  • NumberFormatException: Converting invalid string to number (Integer.parseInt("abc")).
  • ClassNotFoundException: Attempting to load missing class at runtime.
  • IOException: General failure during input/output operations.

5.5 User-defined exceptions

Developers can define domain-specific exceptions by extending java.lang.Exception (checked) or java.lang.RuntimeException (unchecked).

// Custom exception class
class InsufficientBalanceException extends Exception {
    public InsufficientBalanceException(String message) {
        super(message);
    }
}

class BankAccount {
    private double balance = 1000.0;
    public void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException("Withdrawal of NPR " + amount + " exceeds balance NPR " + balance);
        }
        balance -= amount;
        System.out.println("Withdrawal successful! Remaining: " + balance);
    }
}

5.6 Multithreading basics

A thread is a lightweight, independent unit of execution within a program. Multithreading enables concurrent execution of two or more parts of a program for maximum CPU utilization.

Thread Life Cycle

A Java thread passes through several states monitored by the JVM thread scheduler:

  1. New: Thread created (new MyThread()), not yet started.
  2. Runnable: start() called; ready and waiting for CPU allocation.
  3. Running: CPU actively executing thread's run() method.
  4. Blocked / Waiting / Timed Waiting: Waiting for monitor lock, I/O, or sleep()/wait() timer to expire.
  5. Terminated (Dead): run() method completes execution.
stateDiagram-v2
    [*] --> New: new Thread()
    New --> Runnable: start()
    Runnable --> Running: Scheduler yields CPU
    Running --> Runnable: yield() / Time-slice
    Running --> Blocked: wait() / sleep() / Lock blocked
    Blocked --> Runnable: notify() / Timer expires / Lock freed
    Running --> Terminated: run() completes
    Terminated --> [*]

Figure 5.2: Java Thread Life Cycle State Machine.


5.7 Thread class and Runnable interface

Java offers two primary ways to create threads:

Approach 1: Extending java.lang.Thread

class WorkerThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println("WorkerThread count: " + i);
        }
    }
}
// Launching: new WorkerThread().start();

Approach 2: Implementing java.lang.Runnable (Recommended)

Preferred because Java does not support multiple class inheritance; implementing Runnable leaves the class free to extend other classes.

class TaskRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Task running via Runnable interface");
    }
}
// Launching: new Thread(new TaskRunnable()).start();

5.8 Thread priorities

Every thread has a priority represented by an integer from 1 to 10:

  • Thread.MIN_PRIORITY (1)
  • Thread.NORM_PRIORITY (5 - Default)
  • Thread.MAX_PRIORITY (10)

Set via thread.setPriority(int priority). Higher priority threads are preferred by the thread scheduler, though priority handling depends on underlying OS thread scheduling.


5.9 Thread synchronization and inter-thread communication

Race Conditions and Synchronization

When multiple threads read and write shared data concurrently, data corruption occurs. The synchronized keyword enforces mutual exclusion using internal object monitors:

class TicketCounter {
    private int availableTickets = 1;

    // Synchronized method: only one thread can execute this at a time
    public synchronized void bookTicket(String passengerName) {
        if (availableTickets > 0) {
            System.out.println("Ticket booked for " + passengerName);
            availableTickets--;
        } else {
            System.out.println("Sold out! No ticket for " + passengerName);
        }
    }
}

Inter-Thread Communication (wait, notify, notifyAll)

Used to avoid polling loops when threads communicate status:

  • wait(): Releases lock and puts invoking thread to sleep until notified.
  • notify(): Wakes up a single waiting thread.
  • notifyAll(): Wakes up all threads waiting on the object monitor. Note: Must be called from within a synchronized context.

Unit 6: File Handling in Java

Teaching Hours: 6

6.1 Console and file I/O

Java performs Input/Output (I/O) via Streams: logical conduits that produce or consume sequences of data.
Standard Console Streams:

  • System.in: Standard Input Stream (InputStream).
  • System.out: Standard Output Stream (PrintStream).
  • System.err: Standard Error Stream (PrintStream).

6.2 Reading and writing files using byte streams

Byte streams process raw binary data 8 bits (1 byte) at a time. Ideal for media files (images, audio, video, compiled classes). Root abstract classes: InputStream and OutputStream.

// File: ByteStreamCopyDemo.java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteStreamCopyDemo {
    public static void main(String[] args) {
        // Try-with-resources automatically closes streams
        try (FileInputStream in = new FileInputStream("source.jpg");
             FileOutputStream out = new FileOutputStream("destination.jpg")) {
            int byteRead;
            while ((byteRead = in.read()) != -1) {
                out.write(byteRead); // Writes 1 byte at a time
            }
            System.out.println("Binary file copied successfully.");
        } catch (IOException e) {
            System.err.println("I/O Error: " + e.getMessage());
        }
    }
}

6.3 Reading and writing files using character streams

Character streams process text data 16 bits (2 bytes, Unicode) at a time, handling international character sets automatically. Root abstract classes: Reader and Writer.

// File: CharacterStreamDemo.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamDemo {
    public static void main(String[] args) {
        String file = "students.txt";
        // Writing text using BufferedWriter
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write("TU BCA Second Semester - Java Notes\n");
            writer.write("Subject Code: BCA153\n");
        } catch (IOException e) {
            System.err.println("Write error: " + e.getMessage());
        }

        // Reading line-by-line using BufferedReader
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Line: " + line);
            }
        } catch (IOException e) {
            System.err.println("Read error: " + e.getMessage());
        }
    }
}

6.4 Serialization and deserialization

  • Serialization: The process of converting the state of a live Java object into a byte stream for storage (in a file/database) or transmission over a network. The class must implement java.io.Serializable (a marker interface).
  • Deserialization: The reverse process: reconstructing the live Java object in memory from the byte stream.
  • transient Keyword: Fields marked transient are skipped during serialization (e.g., passwords or cached values).
// File: SerializationDemo.java
import java.io.*;

class StudentRecord implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    transient String password; // Will not be saved

    public StudentRecord(String name, String password) {
        this.name = name;
        this.password = password;
    }
}

public class SerializationDemo {
    public static void main(String[] args) throws Exception {
        StudentRecord s1 = new StudentRecord("Suman", "Secret123");

        // Serialize to file
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
            oos.writeObject(s1);
        }

        // Deserialize from file
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
            StudentRecord s2 = (StudentRecord) ois.readObject();
            System.out.println("Name: " + s2.name + " | Password: " + s2.password); // Password is null!
        }
    }
}

6.5 RandomAccessFile class

Unlike standard sequential streams that read from beginning to end, java.io.RandomAccessFile allows non-sequential, random reading and writing anywhere within a file.

  • Operates like a large array of bytes with an internal file pointer.
  • Move pointer using seek(long position).
  • Retrieve current location with getFilePointer().
  • Modes: "r" (read-only), "rw" (read-write).

Unit 7: Collections and Generics

Teaching Hours: 6

7.1 Wrapper classes and associated methods

Wrapper classes convert primitive data types into reference objects (int $ ightarrow$ Integer, char $ ightarrow$ Character, double $ ightarrow$ Double), enabling primitives to be used in generic collections.

  • Autoboxing: Automatic conversion of primitive to wrapper (Integer val = 100;).
  • Unboxing: Automatic conversion of wrapper to primitive (int x = val;).
  • Useful utility methods: Integer.parseInt(str), Double.parseDouble(str), Integer.toBinaryString(val).

7.2 Java collection framework

The Java Collections Framework (JCF) provides an established architecture for storing and manipulating groups of objects.

flowchart TD
    Collection[Collection Interface] --> List[List Interface: Ordered, duplicates allowed]
    Collection --> Set[Set Interface: Unique elements only]
    Collection --> Queue[Queue Interface: FIFO Ordering]
    List --> ArrayList[ArrayList: Dynamic Array]
    List --> LinkedList[LinkedList: Doubly Linked List]
    Set --> HashSet[HashSet: Unordered, Hash Table]
    Set --> TreeSet[TreeSet: Sorted, Red-Black Tree]
    Map[Map Interface: Key-Value Pairs] --> HashMap[HashMap: Unordered Keys]
    Map --> TreeMap[TreeMap: Sorted Keys]

Figure 7.1: The Java Collection Framework Interface and Implementation Hierarchy.

7.2.1 List, Set, Map interfaces

  • List: Ordered collection; maintains insertion order; allows duplicate elements.
  • Set: Unordered collection; strictly prohibits duplicate elements.
  • Map: Not a subtype of Collection; stores data in key-value pairs; keys must be unique.

7.2.2 Core Collection Classes

  • ArrayList: Resizable array. Fast random access $O(1)$; slow insertions/deletions in middle $O(n)$.
  • LinkedList: Doubly linked list. Fast insertions/deletions $O(1)$; slower sequential access $O(n)$.
  • HashSet: Hash-table backed set. Provides constant-time performance $O(1)$ for basic operations.
  • TreeSet: Navigable set backed by Red-Black tree; sorts elements in natural ascending order $O(\log n)$.
  • HashMap: Hash-table based map storing unique keys mapped to values.
// File: CollectionDemo.java
import java.util.*;

public class CollectionDemo {
    public static void main(String[] args) {
        // 1. List Demo
        List<String> cities = new ArrayList<>();
        cities.add("Kathmandu");
        cities.add("Pokhara");
        cities.add("Kathmandu"); // Duplicates allowed

        // 2. Set Demo
        Set<String> uniqueCities = new HashSet<>(cities);
        System.out.println("Unique Cities Count: " + uniqueCities.size()); // 2

        // 3. Map Demo
        Map<String, Integer> cityPin = new HashMap<>();
        cityPin.put("Kathmandu", 44600);
        cityPin.put("Pokhara", 33700);
        System.out.println("Kathmandu PIN: " + cityPin.get("Kathmandu"));
    }
}

7.3 Accessing collections: Iterator/comparator

  • Iterator: An interface providing a standard way to traverse any collection sequentially:
    • hasNext(): Returns true if more elements exist.
    • next(): Returns the next element.
    • remove(): Safely removes current element during traversal.
  • Comparable vs Comparator:
    • Comparable<T>: Defines natural ordering inside the class via compareTo(T o).
    • Comparator<T>: Defines multiple custom sorting strategies outside the class via compare(T o1, T o2).

7.4 Defining generic classes and methods

Generics introduce compile-time type safety, eliminating runtime ClassCastException and manual casting.

// Generic Box class parameterized with type T
class Box<T> {
    private T item;
    public void set(T item) { this.item = item; }
    public T get() { return item; }
}

public class GenericDemo {
    public static void main(String[] args) {
        Box<String> strBox = new Box<>();
        strBox.set("Hello BCA");
        String val = strBox.get(); // No manual casting required!
    }
}

7.5 Using wildcard arguments

Wildcard character ? represents an unknown type in generic parameters:

  1. Unbounded Wildcard (<?>): Can accept any type (List<?> list).
  2. Upper Bounded Wildcard (<? extends Number>): Restricts the unknown type to a specific class or its subclasses (read-safe).
  3. Lower Bounded Wildcard (<? super Integer>): Restricts the unknown type to a specific class or its superclasses (write-safe).

7.6 Generic interface and generic hierarchy

Generics can be applied to interfaces (e.g., Comparable<T>, List<E>). Generic classes can inherit from other generic or non-generic superclasses while maintaining type parameters throughout the hierarchy.


7.7 Some generic restrictions

  1. Cannot instantiate generic types with primitive types directly (List<int> is invalid; use List<Integer>).
  2. Cannot create instances of type parameters (new T()).
  3. Cannot declare static fields whose types are type parameters.
  4. Cannot create arrays of parameterized types (new Box<String>[10]).
  5. Cannot use generics with exception handling (class MyException<T> extends Exception is illegal).

Unit 8: Advanced OOP Concepts in Java

Teaching Hours: 4

8.1 Design patterns: singleton, factory, observer patterns

A design pattern is a reusable, proven architectural solution to a commonly occurring software design problem.

1. Singleton Pattern (Creational)

Ensures a class has only one instance and provides a global point of access to it.

class DatabaseConnection {
    private static DatabaseConnection instance;
    private DatabaseConnection() {} // Private constructor prevents new instantiation

    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }
}

2. Factory Pattern (Creational)

Defines an interface or abstract class for creating objects, letting subclasses decide which concrete class to instantiate.

3. Observer Pattern (Behavioral)

Defines a one-to-many dependency between objects so that when one object (Subject) changes state, all its dependents (Observers) are automatically notified and updated.


8.2 Lambda expressions

Introduced in Java 8, a lambda expression is an anonymous function (a block of code without a name, return type, or class) passed around as data. Requires a Functional Interface (an interface with exactly one abstract method, annotated @FunctionalInterface).

Syntax:

(parameters) -> { body }
// File: LambdaDemo.java
@FunctionalInterface
interface MathOperation {
    int operate(int a, int b);
}

public class LambdaDemo {
    public static void main(String[] args) {
        // Lambda implementation of addition
        MathOperation addition = (a, b) -> a + b;
        System.out.println("Result: " + addition.operate(20, 30)); // 50
    }
}

8.3 Stream API: introduction

The Java Stream API (java.util.stream) provides a declarative, functional approach to processing sequences of elements.
Key characteristics:

  • Streams do not store data; they convey data from a source (collection, array).
  • Intermediate operations (filter, map, sorted) are lazy.
  • Terminal operations (collect, forEach, reduce) produce a result or side-effect.
import java.util.*;
import java.util.stream.Collectors;

public class StreamDemo {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Sita", "Ram", "Hari", "Gita", "Shyam");
        List<String> filtered = names.stream()
            .filter(s -> s.startsWith("S"))
            .map(String::toUpperCase)
            .sorted()
            .collect(Collectors.toList());
        System.out.println("Filtered: " + filtered); // [SHYAM, SITA]
    }
}

8.4 Optional class

Introduced in Java 8, java.util.Optional<T> is a container object that may or may not contain a non-null value. Designed to eradicate NullPointerException by forcing developers to handle empty cases explicitly:

  • Optional.of(value)
  • Optional.ofNullable(value)
  • isPresent(), ifPresent(consumer)
  • orElse(defaultValue)

8.5 Method references

Method references provide a compact, easy-to-read syntax for lambda expressions that merely call an existing method.

  • Syntax: ContainingClass::staticMethodName or instanceReference::methodName.
  • Example: names.forEach(System.out::println); replaces names.forEach(s -> System.out.println(s));.

Comprehensive Practice Questions with Answer Keys

Section A: Short Answer Questions (Exam Style)

Q1. Why is Java architectural neutral?
Answer: Java compiler converts source code into intermediate bytecode (.class) rather than machine-specific native instructions. Any computing system with a platform-compliant Java Virtual Machine (JVM) can interpret and execute this bytecode without modifying or recompiling the original source code.

Q2. What is a jagged array? Write a code snippet to declare one.
Answer: A jagged array is a multi-dimensional array where each row can have a different number of columns.

int[][] jagged = new int[2][];
jagged[0] = new int[3]; // Row 0 has 3 columns
jagged[1] = new int[5]; // Row 1 has 5 columns

Q3. Differentiate between throw and throws.
Answer:

  • throw is used inside a method body to explicitly trigger an exception instance (throw new IOException();).
  • throws is part of a method signature used to declare exceptions that might propagate up to the caller without being caught locally (public void readFile() throws IOException).

Q4. What is the role of serialVersionUID in object serialization?
Answer: serialVersionUID is a unique version identifier for a Serializable class. During deserialization, the JVM verifies that the sender and receiver of a serialized object have loaded classes that are compatible with respect to serialization.


Section B: Long Comprehensive Problem

Q5. Design an Employee Management System demonstrating Inheritance, Encapsulation, Polymorphism, and Interface.

// Interface defining tax calculation behavior
interface Taxable {
    double calculateTax();
}

// Abstract superclass
abstract class Employee {
    private int id;
    private String name;
    protected double basicSalary;

    public Employee(int id, String name, double basicSalary) {
        this.id = id;
        this.name = name;
        this.basicSalary = basicSalary;
    }

    public String getName() { return name; }
    public int getId() { return id; }

    // Abstract method forcing subclass-specific calculation
    public abstract double calculateNetSalary();
}

// Subclass Manager inheriting Employee and implementing Taxable
class Manager extends Employee implements Taxable {
    private double bonus;

    public Manager(int id, String name, double basicSalary, double bonus) {
        super(id, name, basicSalary);
        this.bonus = bonus;
    }

    @Override
    public double calculateTax() {
        return 0.15 * (basicSalary + bonus); // 15% tax rate
    }

    @Override
    public double calculateNetSalary() {
        return (basicSalary + bonus) - calculateTax();
    }
}

public class EmployeeSystemDemo {
    public static void main(String[] args) {
        Employee emp = new Manager(101, "Aayush Sharma", 50000, 15000);
        System.out.println("Employee Name: " + emp.getName());
        System.out.println("Calculated Net Salary: NPR " + emp.calculateNetSalary());
    }
}

References

  • Balagurusamy, E. (2024). Programming with Java (7th ed.). McGraw Hill.
  • Deitel, P. J., & Deitel, H. M. (2024). Java how to program: An objects-natural approach (12th ed.). Pearson.
  • Horstmann, C. S. (2024). Core Java, Volume I: Fundamentals (13th ed.). Addison-Wesley Professional.
  • Schildt, H., & Coward, D. (2024). Java: The complete reference (13th ed.). McGraw Hill.
  • TU Document: https://portal.tu.edu.np/downloads/2025_11_27_15_22_42.pdf (PDF p. 51-56, SHA-256: sha256:02eee32d756f2decf7604fad66b99d508744e055f14d4e480fc2a92327b8062a).\n