Skip to content
Unit 3 Syllabus Note· Object Oriented Programming using JAVA

Object Oriented Programming using JAVA

Comprehensive exam revision notes for BCA-201N Unit 3 (Interfaces, Packages, Arrays, Strings & Wrapper Classes). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Object Oriented Programming using JAVA

Interfaces, Packages, Arrays, Strings & Wrapper Classes

Core Definitions & Key Concepts

What is an interface in Java

An interface is a pure contract specification in Java. In Java 7, it could only contain abstract methods and public static final constants. From Java 8 onward, it can also contain default and static methods; Java 9 introduced private interface methods.

How does an Interface achieve Multiple Inheritance in Java

While a class can extend only one superclass, it can implement multiple interfaces separated by commas (class C implements A, B). Because interfaces do not contain instance state, no diamond conflict occurs over data fields.

What is a 'Marker Interface' (Tagging Interface)

An interface that contains ZERO methods and zero constants (e.g., java.io.Serializable, java.lang.Cloneable). It simply tags or signals to the JVM that the implementing class possesses a specific capability.

What are default methods in Java 8 interfaces

default methods provide a default method body inside an interface (default void log() { ... }). They allow library designers to add new methods to existing interfaces without breaking existing implementing classes.

What is a 'Package' in Java

A package is a named namespace that groups related classes, interfaces, and sub-packages together (e.g., java.util). It prevents naming collisions and provides package-level access control.

What is the difference between String, StringBuilder, and StringBuffer

  • String: Immutable (cannot be modified; every change creates a new heap object), thread-safe.
  • StringBuffer: Mutable (can be modified in-place), thread-safe (all methods synchronized), slower.
  • StringBuilder: Mutable, non-synchronized (not thread-safe), highest performance for single-threaded string concatenation.

What is the 'String Constant Pool' (SCP)

A special memory region inside the Java Heap where string literals are cached. When a string literal is created (String s = "hello"), the JVM checks the pool: if it exists, it returns the pooled reference; otherwise it creates and pools it.

Why are Java String objects Immutable

For Security (parameters cannot be tampered with in network/database connections), Synchronization (thread-safe without locking), Caching (String Constant Pool reuse), and HashCode caching (ideal key for HashMaps).

What is a 'Wrapper Class' in Java

A class that encapsulates a primitive data type into an object (e.g., int -> Integer, char -> Character, double -> Double), allowing primitives to participate in object collections like ArrayList.

What is Autoboxing and Unboxing in Java

  • Autoboxing: Automatic conversion of a primitive to its corresponding wrapper object by the compiler (Integer x = 5;).
  • Unboxing: Automatic conversion of a wrapper object back to its primitive value (int a = x;).

Conceptual & Architectural Analysis

Compare Abstract Classes and Interfaces in Java (Java 8/9+ standard)

CriteriaAbstract ClassInterface
InheritanceSingle inheritance (extends)Multiple inheritance (implements)
VariablesCan have instance, static, and final variablesOnly public static final constants
ConstructorsCan declare constructorsCannot declare constructors
MethodsAbstract and concrete instance methodsAbstract, default, static, private
SpeedSlightly fasterSlight overhead of interface lookup
PurposeCode sharing among closely related classesStandardized contract across unrelated classes

The Creation and Importing of User-Defined Packages with Directory Rules

To create a package, the package statement must be the very first line of code:

Java
1package com.xrounder.academic;
2
3public class SyllabusTracker {
4 public void display() { System.out.println("Syllabus Active"); }
5}
  • Directory Structure Rule: The source file must reside in folder com/xrounder/academic/SyllabusTracker.java.
  • Compilation: javac -d . SyllabusTracker.java generates the folder tree automatically.
  • Usage: Another file imports it via import com.xrounder.academic.SyllabusTracker;.

String Memory Allocation: Literal vs new String()

  • String s1 = "MJPRU"; checks the String Constant Pool. If "MJPRU" exists, s1 references the pooled object. No new object is created on the heap.
  • String s2 = new String("MJPRU"); forces the creation of a brand new object on the non-pool heap, and also ensures "MJPRU" exists in the pool.
  • Therefore, s1 == s2 evaluates to false (comparing memory addresses), whereas s1.equals(s2) evaluates to true (comparing character sequence content).

Array Declaration, Allocation, and Multi-Dimensional (Jagged) Arrays in Java

In Java, arrays are dynamically allocated objects on the heap:

Java
1int[] arr = new int[5]; // Allocated on heap, initialized to 0

Jagged (Ragged) Arrays: Arrays of arrays where rows have differing column lengths:

Java
1int[][] jagged = new int[3][];
2jagged[0] = new int[2]; // Row 0 has 2 elements
3jagged[1] = new int[4]; // Row 1 has 4 elements
4jagged[2] = new int[3]; // Row 2 has 3 elements

Common Methods of the String class with Code Snippets

Core String API methods:

  • length(): Returns character count.
  • charAt(int index): Returns character at index.
  • substring(int start, int end): Extracts slice.
  • contains(CharSequence s): Tests substring presence.
  • toUpperCase() / toLowerCase(): Case transformation.
  • trim(): Trims leading/trailing whitespace.
  • replace(oldChar, newChar): Replaces characters.
  • split(String regex): Splits into array of tokens.

In-Depth Analysis & Implementation

Design and Implement a Modular Payment Processing System Demonstrating Multiple Interface Implementation, Default Methods, and Custom Packages

System Architecture / Concept DiagramHorizontal Scroll Enabled
/**
 * University Examination Model Solution: BCA-201N Unit 3
 * Topic: Interfaces, Default Methods, and Multiple Interface Implementation
 */
interface PaymentGateway {
    boolean processTransaction(double amount);
    
    // Java 8 Default Method
    default void printReceipt(String transactionId, double amount) {
        System.out.println("----------------------------------------");
        System.out.println("         OFFICIAL PAYMENT RECEIPT       ");
        System.out.println("Transaction ID : " + transactionId);
        System.out.printf("Amount Paid    : Rs. %,.2f%n", amount);
        System.out.println("Status         : SUCCESS / VERIFIED");
        System.out.println("----------------------------------------");
    }
}

interface SecurityAudit {
    boolean verifyFingerprint(String token);
    
    static void logSecurityWarning(String message) {
        System.err.println("[SECURITY LOG]: " + message);
    }
}

// Multiple Interface Implementation
class UPIPaymentService implements PaymentGateway, SecurityAudit {
    private String upiId;

    public UPIPaymentService(String upiId) {
        this.upiId = upiId;
    }

    @Override
    public boolean verifyFingerprint(String token) {
        return token != null && token.length() >= 6;
    }

    @Override
    public boolean processTransaction(double amount) {
        if (verifyFingerprint("SEC#9941")) {
            System.out.printf("Processing UPI payment of Rs. %,.2f for VPA: %s...%n", amount, upiId);
            printReceipt("TXN_" + System.currentTimeMillis(), amount);
            return true;
        } else {
            SecurityAudit.logSecurityWarning("Fingerprint validation failed for VPA: " + upiId);
            return false;
        }
    }
}

public class InterfaceApplicationDemo {
    public static void main(String[] args) {
        PaymentGateway upi = new UPIPaymentService("student@sbi");
        upi.processTransaction(15400.0);
    }
}

Write a Detailed Technical Comparison of String Manipulation Classes: String vs StringBuffer vs StringBuilder

1. Architectural Mutability

String is immutable. When concatenating in a loop (str += "x"), the JVM must allocate a new String object, copy characters, and discard the old string, causing severe GC pressure. StringBuffer and StringBuilder maintain an internal resizable char[] buffer with default initial capacity of 16 characters. Append operations modify the buffer in-place without generating garbage.

2. Thread Safety and Synchronization

  • StringBuffer has all public methods marked synchronized (thread-safe, safe for multi-threaded environments, but incurs locking overhead).
  • StringBuilder has no synchronization, yielding peak execution speed for single-threaded string builders.

3. Empirical Benchmark (100,000 Appends)

  • String with +: ~15,000 ms (creates 100,000 objects).
  • StringBuffer: ~12 ms.
  • StringBuilder: ~5 ms.

Jagged Arrays and Write a Java Program to Model and Compute Semester Student Marks

System Architecture / Concept DiagramHorizontal Scroll Enabled
public class JaggedArrayGrades {
    public static void main(String[] args) {
        // 3 Students having 2, 4, and 3 subjects respectively
        int[][] studentMarks = new int[3][];
        studentMarks[0] = new int[] {85, 92};
        studentMarks[1] = new int[] {78, 88, 91, 84};
        studentMarks[2] = new int[] {90, 82, 89};

        System.out.println("Student Marks Summary (Jagged Array):");
        for (int i = 0; i < studentMarks.length; i++) {
            int total = 0;
            System.out.printf("Student %d: ", (i + 1));
            for (int j = 0; j < studentMarks[i].length; j++) {
                System.out.print(studentMarks[i][j] + " ");
                total += studentMarks[i][j];
            }
            double avg = (double) total / studentMarks[i].length;
            System.out.printf("| Total: %d | Avg: %.2f%n", total, avg);
        }
    }
}

Important Exam Points & Quick Revision

Be clear on String Constant Pool, difference between == and equals(), and why String is immutable. Interface multiple inheritance is a top exam topic.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Interfaces, Packages, Arrays, Strings & Wrapper Classes.

Weak topic hint

Interfaces, Packages, Arrays, Strings & Wrapper Classes still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.