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
| Aspect | Procedural Programming | Object-Oriented Programming |
|---|---|---|
| Structure | Sequence of functions/procedures | Collaborating objects (data + behaviour) |
| Data & Code | Kept separate; global data exposed | Data encapsulated inside objects |
| Design | Top-down | Bottom-up |
| Scalability | Hard to maintain as code grows | Scales well; promotes reuse |
| Examples | C, Pascal, BASIC, FORTRAN | Java, 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
- Reusability – Inherit and compose existing classes.
- Modularity – Independent objects can be developed, tested and replaced separately.
- Maintainability – Localised changes; well-defined interfaces reduce ripple effects.
- Scalability – New features added by extending classes.
- Security – Encapsulation hides data; access modifiers protect internal state.
2. Java Variables and Data Types
Primitive Data Types
| Type | Size | Default | Range / Notes |
|---|---|---|---|
| byte | 1 byte | 0 | -128 to 127 |
| short | 2 bytes | 0 | -32,768 to 32,767 |
| int | 4 bytes | 0 | ≈ ±2.1 billion |
| long | 8 bytes | 0L | Very large integers (suffix L) |
| float | 4 bytes | 0.0f | Single-precision (suffix f) |
| double | 8 bytes | 0.0d | Double-precision (default decimal) |
| char | 2 bytes | '\u0000' | Single Unicode character |
| boolean | 1 bit* | false | true 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:
newallocates heap memory.- Constructor runs to initialise fields.
- Reference stored on the stack.
Object Lifecycle
- Declaration →
Student s; - Instantiation →
new - Initialization → constructor runs
- Usage → call methods
- 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 theString[]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+:
defaultandstaticmethods allowed. - No constructors.
Abstract Class vs Interface
| Aspect | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract class | interface |
| Multiple inheritance | No | Yes |
| Fields | Any kind | public static final only |
| Methods | Abstract + concrete | Abstract + default/static |
| Constructor | Yes | No |
| Use when | Shared base + state | Pure 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
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| private | Yes | — | — | — |
| default | Yes | Yes | — | — |
| protected | Yes | Yes | Yes | — |
| public | Yes | Yes | Yes | Yes |
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.
| Type | Mechanism | Binding |
|---|---|---|
| Compile-time (Static) | Method Overloading | Early / Static |
| Runtime (Dynamic) | Method Overriding | Late / Dynamic |
Method Overriding Rules
- Same name, parameters and return type (or covariant).
- Access cannot be more restrictive.
- Only inherited non-final methods.
static/privateare 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 sound11. OOP Summary – Four Pillars
| Pillar | Idea | Java Mechanism | Real-World Example |
|---|---|---|---|
| Abstraction | Hide complexity, show essentials | abstract class, interface | ATM withdraw button |
| Encapsulation | Protect & bundle data | private + getters/setters | Bank account balance |
| Inheritance | Reuse via IS-A hierarchy | extends, super | Car IS-A Vehicle |
| Polymorphism | One name, many forms | overloading / overriding | Animal.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
| Method | Returns |
|---|---|
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
| Primitive | Wrapper |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
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 → falseAlways 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
| Policy | Behaviour |
|---|---|
| SOURCE | Discarded by compiler |
| CLASS | Kept in .class, not available at runtime |
| RUNTIME | Available via reflection |
Built-in Annotations
| Annotation | Purpose |
|---|---|
@Override | Verifies method overrides a superclass method |
@Deprecated | Marks element obsolete; warns on use |
@SuppressWarnings | Silences specific compiler warnings |
@FunctionalInterface | Enforces 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, LinkedHashMapQuick Comparison
| Type | Order | Duplicates | Get | Add |
|---|---|---|---|---|
| ArrayList | Index | Yes | O(1) | O(1)* |
| LinkedList | Insert | Yes | O(n) | O(1) |
| HashSet | None | No | — | O(1) |
| TreeSet | Sorted | No | — | O(log n) |
| HashMap | None | Keys unique | O(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
- Overloading vs Overriding?
- Abstract class vs Interface?
- Why no multiple class inheritance?
- Integer cache range? (-128 to 127)
- HashMap vs TreeMap complexity?
- Enum constructor access? → private
- List allows duplicates? → Yes
- Sorted Set implementation? → TreeSet
@Retentionfor reflection? → RUNTIME- 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
Advanced Java Index
Complete unit-wise directory mapping interactive concept guides, question banks, and source PDFs -> Generated and Prepared By Thiruselvan (ThiruXD).
Adv-Java Unit 1: Questions & Answers
Unit 1: Object-Oriented Programming Concepts, Enumerations, Autoboxing, Annotations & Collections Framework -> Generated and Prepared By Thiruselvan (ThiruXD)