BTCE | 5th Sem
Adv-Java SubjectUnit 1

Adv-Java Unit 1: Complete Concept Guide

Unit 1: Object-Oriented Programming Concepts, Enumerations, Autoboxing, Annotations & Collections Framework -> Generated and Prepared By Thiruselvan (ThiruXD)

1. Introduction to Object-Oriented Programming

Procedural vs Object-Oriented

AspectProcedural ProgrammingObject-Oriented Programming
StructureSequence of functions/proceduresCollaborating objects (data + behaviour)
Data & CodeKept separate; global data exposedData encapsulated inside objects
DesignTop-downBottom-up
ScalabilityHard to maintain as code growsScales well; promotes reuse
ExamplesC, Pascal, BASIC, FORTRANJava, C++, C#, Python

Why OOP?

Large systems map naturally to real-world entities (Student, Account, Order). OOP manages complexity through encapsulation, reuse via inheritance, and flexibility via polymorphism.

Characteristics / Four Pillars of OOP

  • Class
  • Object
  • Abstraction
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Message Passing

Benefits of OOP

  1. Reusability – Inherit and compose existing classes.
  2. Modularity – Independent objects can be developed, tested and replaced separately.
  3. Maintainability – Localised changes; well-defined interfaces reduce ripple effects.
  4. Scalability – New features added by extending classes.
  5. Security – Encapsulation hides data; access modifiers protect internal state.

2. Java Variables and Data Types

Primitive Data Types

TypeSizeDefaultRange / Notes
byte1 byte0-128 to 127
short2 bytes0-32,768 to 32,767
int4 bytes0≈ ±2.1 billion
long8 bytes0LVery large integers (suffix L)
float4 bytes0.0fSingle-precision (suffix f)
double8 bytes0.0dDouble-precision (default decimal)
char2 bytes'\u0000'Single Unicode character
boolean1 bit*falsetrue or false (*JVM-dependent)

Non-Primitive (Reference) Types

Classes, Interfaces, Arrays, Strings, Enums.

  • Store references (addresses), not raw values.
  • Default value is null.
  • Created with new.

Variable Types

  • Local – Declared inside a method/block; visible only there; must be initialised.
  • Instance – Declared in class but outside methods; each object has its own copy.
  • Static – Declared with static; shared among all instances; memory allocated once when class loads.

Stack vs Heap

Primitives and references live on the stack; objects live on the heap.


3. Classes and Objects

Definitions

  • Class → Blueprint/template defining state (fields) + behaviour (methods).
  • Object → Concrete instance of a class in memory. One class → many independent objects.

UML Class Diagram Example

Student
- rollNo : int
- name : String
- gpa : double
+ enroll() : void
+ getGpa() : double
+ display() : void

(- = private, + = public)

Creating Objects

Student s1 = new Student(101, "Asha");

Steps:

  1. new allocates heap memory.
  2. Constructor runs to initialise fields.
  3. Reference stored on the stack.

Object Lifecycle

  1. Declaration → Student s;
  2. Instantiation → new
  3. Initialization → constructor runs
  4. Usage → call methods
  5. Garbage Collection → when no live references remain (s = null;)

Java reclaims memory automatically. An object becomes eligible for GC when no live reference points to it.


4. Constructors

Purpose & Rules

  • Special method that initialises a new object.
  • Same name as the class; no return type (not even void).
  • Invoked automatically with new.
  • Can be overloaded.
  • If you write none → Java provides a default no-arg constructor.
  • Writing any constructor removes the implicit default.
  • this(...) chains constructors; super(...) calls the parent.

Types

  • Default / No-argument
  • Parameterized
  • Copy (conceptually – builds object from another object’s state)

Example

class Box {
    int w, h;
    Box() { w = 1; h = 1; }                    // no-arg
    Box(int w, int h) { this.w = w; this.h = h; } // parameterized
    Box(Box b) { this.w = b.w; this.h = b.h; }    // copy
    int area() { return w * h; }
}

5. Method Overloading (Compile-time Polymorphism)

Rules

  • Same method name, different parameter list (number, type or order).
  • Return type alone is not enough.
  • Resolved by the compiler (static / early binding).
class Calculator {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
    int add(int a, int b, int c) { return a + b + c; }
}

Interview Points

  • Can methods be overloaded by return type only? → No.
  • Is main() overloadable? → Yes, but JVM calls the String[] version.
  • Overloading vs Overriding → Compile-time vs Runtime.

6. Abstraction

Definition

Hiding implementation details and exposing only essential features. Users see “what”, not “how”.

Achieved by

  • Abstract classes
  • Interfaces

Abstract Classes

abstract class Shape {
    abstract double area();          // no body
    void describe() {                // concrete method
        System.out.println("Area = " + area());
    }
}
class Circle extends Shape {
    double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}
  • Declared with abstract.
  • Can mix abstract + concrete methods.
  • Cannot be instantiated.
  • Subclass must override all abstract methods (or be abstract itself).
  • Can have constructors, fields and static members.
  • Cannot be final.

7. Interfaces

Features

  • Pure contract (method signatures).
  • All members public by default; fields are public static final.
  • A class may implement many interfaces → multiple inheritance of type.
  • Java 8+: default and static methods allowed.
  • No constructors.

Abstract Class vs Interface

AspectAbstract ClassInterface
Keywordabstract classinterface
Multiple inheritanceNoYes
FieldsAny kindpublic static final only
MethodsAbstract + concreteAbstract + default/static
ConstructorYesNo
Use whenShared base + statePure capability contract

Multiple Implementation Example

interface Payable { double pay(); }
interface Taxable { double tax(); }

class Employee implements Payable, Taxable {
    double salary;
    Employee(double s) { salary = s; }
    public double pay() { return salary; }
    public double tax() { return salary * 0.1; }
}

8. Encapsulation

Data Hiding

Bundle data + methods in one class. Make fields private; expose controlled getters/setters. Validate inside setters.

Access Modifiers

ModifierClassPackageSubclassWorld
privateYes———
defaultYesYes——
protectedYesYesYes—
publicYesYesYesYes

Bank Account Case Study

class BankAccount {
    private long accNo;
    private double balance;
    public void deposit(double amt) {
        if (amt > 0) balance += amt;
    }
    public boolean withdraw(double amt) {
        if (amt > 0 && amt <= balance) {
            balance -= amt; return true;
        }
        return false;
    }
    public double getBalance() { return balance; }
}

Benefits: Protects state, enables validation, improves security and testability.


9. Inheritance

Definition

Child class acquires fields and methods of a parent. Models the IS-A relationship. Keyword: extends. super accesses the parent.

Types in Java

  • Single
  • Multilevel
  • Hierarchical
  • Multiple (only through interfaces)

Why no multiple class inheritance?

Diamond problem (ambiguity). Java allows multiple interfaces instead.

Constructor Chaining

super() runs first. Default super() is inserted automatically if not written. A constructor cannot call both this() and super().


10. Polymorphism

Definition

“Many forms” – one interface, multiple behaviours.

TypeMechanismBinding
Compile-time (Static)Method OverloadingEarly / Static
Runtime (Dynamic)Method OverridingLate / Dynamic

Method Overriding Rules

  • Same name, parameters and return type (or covariant).
  • Access cannot be more restrictive.
  • Only inherited non-final methods.
  • static / private are not overridden.
  • Use @Override (recommended).

Dynamic Method Dispatch

Parent reference → child object. JVM resolves the call at runtime based on the actual object, not the reference type. Enables “program to an interface”.

Animal[] zoo = { new Dog(), new Cat(), new Animal() };
for (Animal a : zoo) a.sound();   // Bark, Meow, Some sound

11. OOP Summary – Four Pillars

PillarIdeaJava MechanismReal-World Example
AbstractionHide complexity, show essentialsabstract class, interfaceATM withdraw button
EncapsulationProtect & bundle dataprivate + getters/settersBank account balance
InheritanceReuse via IS-A hierarchyextends, superCar IS-A Vehicle
PolymorphismOne name, many formsoverloading / overridingAnimal.sound()

12. Enumerations (Enums)

What is an Enum?

A special type for a fixed set of named constants. Each constant is a singleton object of the enum type. Declared with enum.

Why use Enums?

  • Type-safe (only valid values compile)
  • Readable
  • Usable in switch, loops and collections

Key Facts

  • Constants are implicitly public static final.
  • Implicitly extend java.lang.Enum.
  • Cannot extend another class.
  • Compared safely with ==.

Important Methods

MethodReturns
values()Array of all constants
valueOf(s)Constant matching name s
ordinal()Zero-based position
name()Exact name of the constant
compareTo()Order by ordinal

valueOf() is case-sensitive and throws IllegalArgumentException for unknown names.

Advanced Features

Enums can have fields, private constructors and methods:

enum Planet {
    EARTH(9.81), MARS(3.71), MOON(1.62);
    private final double gravity;
    Planet(double g) { gravity = g; }
    double weight(double mass) { return mass * gravity; }
}

Constructor is always private. Enums can implement interfaces and be used in switch expressions.


13. Autoboxing and Unboxing

Definitions

  • Autoboxing → Primitive → Wrapper object (automatic).
  • Unboxing → Wrapper object → Primitive (automatic).

Primitive ↔ Wrapper Mapping

PrimitiveWrapper
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Why needed?

Generics and Collections store objects, not primitives. List<Integer> needs Integer, not int.

Internal Working

Compiler inserts Wrapper.valueOf(x). Integers from -128 to 127 are cached and reused.

Cache Pitfall

Integer x = 100, y = 100;   // x == y → true (cached)
Integer p = 200, q = 200;   // p == q → false

Always compare wrappers with .equals().

Null Danger

Unboxing a null wrapper throws NullPointerException. Guard nullable wrappers before arithmetic.

Performance

Boxing/unboxing has CPU + memory cost. Prefer primitives in tight loops and hot paths.


14. Annotations

Definition

Metadata attached to code. Does not change program logic directly. Read by compiler, tools or frameworks. Written with @.

Benefits

  • Reduce boilerplate & XML configuration
  • Catch errors early (@Override)
  • Enable declarative, readable code

Retention Policies

PolicyBehaviour
SOURCEDiscarded by compiler
CLASSKept in .class, not available at runtime
RUNTIMEAvailable via reflection

Built-in Annotations

AnnotationPurpose
@OverrideVerifies method overrides a superclass method
@DeprecatedMarks element obsolete; warns on use
@SuppressWarningsSilences specific compiler warnings
@FunctionalInterfaceEnforces single abstract method (for lambdas)

Meta-Annotations

  • @Retention – lifecycle
  • @Target – where it can be applied
  • @Inherited – inherited by subclasses
  • @Documented – included in Javadoc

Custom Annotation Example

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Author {
    String name();
    String date() default "2025-01-01";
}

15. Collections Framework

Need

Arrays are fixed-size. Collections grow/shrink dynamically, provide ready algorithms (sort, search, iterate) and standard interfaces.

Architecture

Iterable
  └── Collection
        ├── List   (ArrayList, LinkedList)
        ├── Set    (HashSet, TreeSet)
        └── Queue  (PriorityQueue, Deque)
        
Map (separate hierarchy) → HashMap, TreeMap, LinkedHashMap

Quick Comparison

TypeOrderDuplicatesGetAdd
ArrayListIndexYesO(1)O(1)*
LinkedListInsertYesO(n)O(1)
HashSetNoneNo—O(1)
TreeSetSortedNo—O(log n)
HashMapNoneKeys uniqueO(1)O(1)

(*amortised)

Interview Tips

  • ArrayList → frequent reads
  • LinkedList → many insertions/deletions
  • HashMap → average O(1); TreeMap keeps keys sorted
  • Set automatically removes duplicates

16. Exam Quick Revision

High-frequency questions

  1. Overloading vs Overriding?
  2. Abstract class vs Interface?
  3. Why no multiple class inheritance?
  4. Integer cache range? (-128 to 127)
  5. HashMap vs TreeMap complexity?
  6. Enum constructor access? → private
  7. List allows duplicates? → Yes
  8. Sorted Set implementation? → TreeSet
  9. @Retention for reflection? → RUNTIME
  10. Unbox null wrapper? → NullPointerException

Four Pillars (must remember)

Abstraction · Encapsulation · Inheritance · Polymorphism

Key Mechanisms

  • Encapsulation → private + getters/setters
  • Inheritance → extends + super
  • Polymorphism → overloading (compile-time) + overriding (runtime)
  • Abstraction → abstract class / interface
  • Enums → type-safe constants + values() / valueOf()
  • Autoboxing → primitive ↔ wrapper bridge
  • Annotations → metadata for tools/compilers
  • Collections → choose List / Set / Queue / Map wisely

On this page