☕
Chapter 1.1 — Java Fundamentals
☕ CHAPTER 1.1 — JAVA FUNDAMENTALS MIND MAP
Java → Platform-independent (bytecode+JVM), OOP, no pointers, auto Garbage Collection
C++ vs Java → Platform-dependent vs independent, pointers, manual vs auto memory, multiple inheritance
Tokens → Keywords, Identifiers, Literals, Operators, Separators
Data Types → 8 primitives (byte→boolean) + Non-primitive (String, Array, Class)
Access Specifiers → public(everywhere) → protected(package+subclass) → default(package) → private(class only)
1. Introduction to Java
📖 Java: A high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle) in 1995. Follows the principle "Write Once, Run Anywhere" (WORA).
| Feature | Description |
| Platform Independent | Compiled to bytecode, runs on any device with a JVM |
| Object-Oriented | Everything (except primitives) is modeled as objects |
| Simple | No pointers, no manual memory management (automatic Garbage Collection) |
| Secure | No explicit pointers, runs in a sandboxed JVM environment |
| Robust | Strong memory management, exception handling, type-checking |
| Multithreaded | Built-in support for concurrent execution |
MyProgram.java --[javac]--> MyProgram.class (bytecode) --[JVM]--> Output
(runs on ANY OS)
Fig: Java Compilation & Execution — Platform Independence
💡 Exam Tip: Java achieves platform independence via BYTECODE (.class files) + JVM — the compiler (javac) doesn't produce machine code directly, it produces bytecode that any JVM (Windows/Linux/Mac) can interpret/execute.
2. Difference Between C++ and Java
| Feature | C++ | Java |
| Platform Dependency | Platform-dependent (compiled to native machine code) | Platform-independent (compiled to bytecode, runs via JVM) |
| Pointers | Explicit pointers supported | No explicit pointers (references used internally, hidden from programmer) |
| Memory Management | Manual (new/delete) | Automatic (Garbage Collector) |
| Multiple Inheritance | Supported directly (via classes) | NOT supported via classes; achieved via Interfaces |
| Operator Overloading | Supported | NOT supported |
| Compilation | Compiles directly to machine code | Compiles to bytecode (.class), then interpreted/JIT-compiled by JVM |
| Global Variables/Functions | Allowed outside classes | Everything must be inside a class |
| Thread Support | Depends on OS/library | Built-in (Thread class, Runnable interface) |
💡 Exam Tip: The TOP 3 most-asked differences: (1) Platform independence — bytecode vs native code, (2) Pointers — Java hides them for safety, (3) Multiple inheritance — C++ allows via classes, Java only via interfaces.
3. Keywords & Tokens
📖 Token: The smallest individual unit of a Java program that the compiler can recognize — the basic building blocks of source code.
📖 Keyword: A reserved word with a predefined meaning in Java — cannot be used as an identifier (variable/class/method name).
| Type of Token | Examples |
| Keywords | class, public, static, void, int, if, else, new, extends |
| Identifiers | Names given by the programmer — variable names, class names, method names |
| Literals | Fixed constant values — 10, 3.14, 'A', "Hello", true |
| Operators | +, -, *, /, =, ==, &&, || |
| Separators/Punctuators | { }, ( ), [ ], ; , . |
Java has 53 reserved keywords total (as of recent versions) — including things like class, public, private, static, void, new, this, super, try, catch, throw, throws.
💡 Exam Tip: "true", "false", and "null" are technically LITERALS, not keywords, in Java's formal grammar — a subtle but sometimes-tested distinction. "const" and "goto" ARE reserved as keywords but are NOT actually used/implemented in Java.
4. Data Types in Java
📖 Data Type: Specifies the type and size of data a variable can hold.
| Type | Size | Example |
| byte | 1 byte | byte b = 10; |
| short | 2 bytes | short s = 1000; |
| int | 4 bytes | int i = 100000; |
| long | 8 bytes | long l = 100000L; |
| float | 4 bytes | float f = 3.14f; |
| double | 8 bytes | double d = 3.14159; |
| char | 2 bytes (Unicode) | char c = 'A'; |
| boolean | 1 bit (JVM-dependent) | boolean flag = true; |
| Category | Types Included |
| Primitive (8 types) | byte, short, int, long, float, double, char, boolean |
| Non-Primitive (Reference) | String, Arrays, Classes, Interfaces |
💡 Exam Tip: char in Java is 2 bytes (Unicode, supports international characters) — NOT 1 byte like in C/C++ (ASCII only). This exact distinction is a common comparison question.
5. Use of public, private, and protected
📖 Access Specifiers: Keywords that control the VISIBILITY/accessibility of classes, methods, and variables from other parts of a program.
| Specifier | Same Class | Same Package | Subclass (diff. package) | Other Package |
| public | ✅ | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ✅ | ❌ |
| default (no modifier) | ✅ | ✅ | ❌ | ❌ |
| private | ✅ | ❌ | ❌ | ❌ |
public class BankAccount {
private double balance; // only accessible within THIS class
protected String accountType; // accessible in same package + subclasses
public String ownerName; // accessible from ANYWHERE
private void updateBalance() { } // hidden implementation detail
public double getBalance() { return balance; } // controlled access (getter)
}
💡 Exam Tip: private is the MOST restrictive (only within the same class); public is the LEAST restrictive (accessible everywhere). This is exactly how Encapsulation is implemented — mark fields private, expose controlled access via public getter/setter methods.
🔗
Chapter 1.2 — OOPS using Java
🔗 CHAPTER 1.2 — OOPS USING JAVA MIND MAP
Class vs Object → Blueprint vs Instance; "new" = allocate+construct+return reference
Inheritance → extends keyword; Single/Multilevel/Hierarchical supported, Multiple NOT (via class)
Abstraction → hide implementation; Abstract class (partial) vs Interface (full)
Polymorphism → Overloading(compile-time) vs Overriding(runtime)
Encapsulation → private fields + public getter/setter = data privacy
Static vs Non-Static → Method Area(1 copy, shared) vs Heap(1 copy per object)
Multiple Inheritance → via Interfaces (implements) — avoids Diamond Problem
1. Classes, Objects & the "new" Keyword
📖 Class: A BLUEPRINT/template that defines the properties (fields) and behaviors (methods) an object of that type will have. No memory is allocated just by defining a class.
📖 Object: A concrete INSTANCE of a class, created at runtime — has actual memory allocated and real values for its fields.
| Feature | Class | Object |
| Definition | Blueprint/template | Instance of the class |
| Memory | No memory allocated | Memory allocated (on heap) |
| Declared using | class keyword | new keyword |
| Count | Only ONE class definition | MANY objects can be created from one class |
class Student { // CLASS = blueprint
String name;
int rollNo;
void display() {
System.out.println(name + " - " + rollNo);
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // OBJECT created using "new"
s1.name = "Ankush";
s1.rollNo = 101;
s1.display();
Student s2 = new Student(); // ANOTHER separate object
s2.name = "Priya";
s2.rollNo = 102;
}
}
Purpose of the "new" Keyword:
The "new" keyword does 3 things:
1. Allocates MEMORY on the heap for a new object
2. Calls the class's CONSTRUCTOR to initialize the object
3. Returns a REFERENCE to that newly created object, which gets stored in a variable
💡 Exam Tip: Without "new", you only have a REFERENCE variable (like Student s1;) pointing to nothing (null) — no actual object exists in memory until "new" is used. This exact "purpose of new" question is directly PYQ-tested.
2. Inheritance
📖 Inheritance: A mechanism where a new class (subclass/child) acquires the properties and methods of an existing class (superclass/parent), using the extends keyword — promotes code reusability.
class Animal { // Superclass (parent)
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal { // Subclass (child) — inherits from Animal
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited from Animal
d.bark(); // Dog's own method
}
}
| Type | Structure | Java Support |
| Single | One child, one parent | ✅ Supported |
| Multilevel | Chain: A→B→C | ✅ Supported |
| Hierarchical | One parent, multiple children | ✅ Supported |
| Multiple | One child, multiple parent CLASSES | ❌ NOT supported directly (only via Interfaces) |
💡 Exam Tip: Java does NOT support multiple class inheritance to avoid the "Diamond Problem" (ambiguity when two parent classes have a method with the same name) — this is exactly why Interfaces exist as the workaround (covered in Section 8).
3. Abstraction
📖 Abstraction: Hiding the internal IMPLEMENTATION details and showing only the essential FEATURES/functionality to the user — "what it does", not "how it does it."
abstract class Shape { // abstract class
abstract double area(); // abstract method - no body!
void display() { // regular method - has body
System.out.println("This is a shape");
}
}
class Circle extends Shape {
double radius = 5;
double area() { // MUST override abstract method
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape s = new Circle();
System.out.println(s.area()); // 78.53...
}
}
| Way to Achieve | Abstraction Level |
| Abstract Class (0-100% abstraction) | Can have BOTH abstract methods (no body) and regular methods (with body) |
| Interface (100% abstraction, traditionally) | All methods are abstract by default (implicitly public+abstract) |
💡 Exam Tip: An abstract class CANNOT be instantiated directly (new Shape() is illegal) — you can only create objects of its concrete subclasses that implement all abstract methods.
4. Polymorphism
📖 Polymorphism: "Many forms" — the ability of an object/method to take on multiple forms/behaviors depending on context.
| Type | Also Called | Achieved via | Resolved at |
| Compile-time | Static Polymorphism | Method Overloading | Compile time |
| Runtime | Dynamic Polymorphism | Method Overriding | Run time |
// Runtime Polymorphism Example
class Animal {
void sound() { System.out.println("Animal makes a sound"); }
}
class Cat extends Animal {
void sound() { System.out.println("Cat meows"); } // overridden
}
public class Main {
public static void main(String[] args) {
Animal a = new Cat(); // Parent reference, Child object
a.sound(); // Output: "Cat meows" (decided at RUNTIME)
}
}
💡 Exam Tip: "Parent reference pointing to Child object" (Animal a = new Cat();) calling an overridden method is the CLASSIC runtime polymorphism example examiners look for — the actual method called depends on the OBJECT's real type, not the reference's declared type.
5. Encapsulation & Data Privacy
📖 Encapsulation: Bundling data (fields) and the methods that operate on that data together into a SINGLE unit (class), while restricting direct access to the data from outside — achieved by making fields private and providing public getter/setter methods.
class BankAccount {
private double balance; // DATA HIDDEN (private)
public double getBalance() { // controlled READ access
return balance;
}
public void deposit(double amount) { // controlled WRITE access
if (amount > 0) { // validation logic!
balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
acc.deposit(500);
// acc.balance = -1000; ❌ NOT ALLOWED (private)
System.out.println(acc.getBalance()); // ✅ Allowed via getter
}
}
✅ Why Encapsulation Matters — Data Privacy:
Without encapsulation, any code could directly set balance = -1000, bypassing all validation. With private fields + public methods, the class CONTROLS exactly how its data can be changed — preventing invalid/inconsistent states.
💡 Exam Tip: Encapsulation is often confused with Abstraction — Encapsulation is about HIDING DATA (private fields + controlled access); Abstraction is about HIDING IMPLEMENTATION COMPLEXITY (showing only what's necessary). They work together but solve different problems.
6. Method Overloading vs Method Overriding
| Feature | Overloading | Overriding |
| Definition | Same method name, DIFFERENT parameters, SAME class | Same method name+parameters, redefined in SUBCLASS |
| Relationship | Within the SAME class | Between PARENT and CHILD class (inheritance required) |
| Polymorphism Type | Compile-time (Static) | Runtime (Dynamic) |
| Parameters | MUST differ (number/type/order) | MUST be identical to parent's method |
| Return Type | Can differ | Must be same (or covariant) |
// OVERLOADING (same class, different parameters)
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // different params
int add(int a, int b, int c) { return a + b + c; }
}
// OVERRIDING (parent-child, same signature)
class Animal {
void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Bark"); } // same signature, redefined
}
💡 Exam Tip: Quick memory trick — "Overloading = Same class, differing parameters (compile-time)"; "Overriding = Different classes (inheritance), identical signature (run-time)." This differentiation is one of the MOST commonly asked 2-mark questions in Java exams.
7. Static vs Non-Static Members — Memory Management
📖 Static Member: Belongs to the CLASS itself, not to any individual object — shared by ALL instances.
📖 Non-Static (Instance) Member: Belongs to a SPECIFIC object — each object gets its OWN separate copy.
class Student {
static String schoolName = "ABC School"; // STATIC - shared by all
String name; // NON-STATIC - unique per object
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Ankush");
Student s2 = new Student("Priya");
System.out.println(s1.schoolName); // ABC School
System.out.println(s2.schoolName); // ABC School (SAME copy)
Student.schoolName = "XYZ School"; // change via class name
System.out.println(s1.schoolName); // XYZ School (changed for BOTH!)
}
}
Memory Management — Where Each Lives:
| Member Type | Memory Area | Number of Copies | Access |
| Static | Method Area (Class Area) — allocated ONCE when class is loaded | Only ONE copy, shared across all objects | Via ClassName.member (or object, but not recommended) |
| Non-Static (Instance) | Heap — allocated separately for EACH object created via "new" | One SEPARATE copy per object | Via object reference only |
✅ Why This Matters for Memory: If you create 1000 Student objects, each gets its OWN copy of "name" (1000 copies in heap) — but "schoolName" exists as just ONE single copy in the Method Area, shared and referenced by all 1000 objects, saving significant memory.
💡 Exam Tip: Static members are loaded into memory ONCE, at class-loading time (before any object even exists) — this is exactly why static methods can be called using the ClassName directly (e.g. Math.sqrt()) without ever creating a Math object.
8. Multiple Inheritance via Interfaces
📖 Interface: A completely abstract "contract" — declares method signatures WITHOUT implementation (traditionally). A class implements an interface and provides the actual method bodies.
❌ Why Java Disallows Multiple CLASS Inheritance: The "Diamond Problem" — if class C extends both class A and class B, and BOTH A and B have a method with the SAME name but DIFFERENT implementations, the compiler cannot decide which version C should inherit → ambiguity.
Worked Example — Multiple Inheritance Using 2 Interfaces:
interface Flyable {
void fly(); // abstract method (no body)
}
interface Swimmable {
void swim(); // abstract method (no body)
}
// A class CAN implement MULTIPLE interfaces — this IS Java's version
// of "multiple inheritance"
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flies short distances");
}
public void swim() {
System.out.println("Duck swims well");
}
}
public class Main {
public static void main(String[] args) {
Duck d = new Duck();
d.fly(); // Duck flies short distances
d.swim(); // Duck swims well
}
}
✅ Why Interfaces AVOID the Diamond Problem: Since (traditionally) interfaces only declare method SIGNATURES with NO implementation, there's nothing conflicting to inherit — the implementing class (Duck) itself provides the ONE actual implementation for each method. Even if Flyable and Swimmable both declared a method with the same name, Duck would simply provide ONE single implementation satisfying both — no ambiguity.
| Feature | Multiple Class Inheritance (C++) | Multiple Interface Implementation (Java) |
| Ambiguity risk | High (Diamond Problem) | None — implementing class provides single implementation |
| Code reuse | Inherits actual implementation from parents | Only inherits method signatures (contracts) |
| Java Support | ❌ Not allowed | ✅ Fully supported |
💡 Exam Tip: This exact question ("demonstrate multiple inheritance using 2 interfaces + explain why preferred over class inheritance") is a confirmed PYQ style — always show a WORKING code example with 2 interfaces implemented by 1 class, THEN explain the Diamond Problem avoidance.
🛡️
Chapter 1.3 — Exception Handling
🛡️ CHAPTER 1.3 — EXCEPTION HANDLING MIND MAP
Error vs Exception → both extend Throwable; Error=unrecoverable, Exception=recoverable
try/catch/throw → try=risky code, catch=handle it, throw=manually trigger one exception object
throw vs throws → throw=action(1 object, inside method), throws=declaration(signature, multiple allowed)
Checked vs Unchecked → Checked=compiler-forced(IOException), Unchecked=RuntimeException subclasses
Why Catch? → prevents crash, better UX, resource cleanup, program continuity
1. Introduction to Exceptions & Error vs Exception
📖 Exception: An unwanted/unexpected event that disrupts the NORMAL flow of program execution — e.g. dividing by zero, accessing an invalid array index.
| Feature | Error | Exception |
| Recoverable? | NO — usually cannot be handled/recovered from | YES — can be caught and handled by the program |
| Cause | Serious problems OUTSIDE the application's control (JVM/system level) | Problems within the application logic itself |
| Examples | OutOfMemoryError, StackOverflowError | ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException |
| Package | java.lang.Error | java.lang.Exception |
| Common Parent | Both extend java.lang.Throwable |
Throwable
/ \
Error Exception
(unrecoverable) / \
Checked Unchecked
(compile-time) (runtime, RuntimeException)
Fig: Java's Throwable Class Hierarchy
💡 Exam Tip: Both Error and Exception extend the common parent class Throwable — this shared ancestry is exactly why questions about "the exception hierarchy" always start from Throwable at the top.
2. Use of try, catch, and throw
📖 try: Encloses the code that MIGHT throw an exception.
📖 catch: Catches and HANDLES a specific exception thrown inside the try block.
📖 throw: Used to MANUALLY/explicitly throw an exception object.
public class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program continues normally...");
}
}
// Output:
Error: Index 5 out of bounds for length 3
Program continues normally...
Manually Throwing an Exception (throw):
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote"); // MANUAL throw
}
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
checkAge(15); // throws exception, program terminates (uncaught)
}
}
try-catch-finally:
finally block: Always executes, whether an exception occurred or not — commonly used for cleanup (closing files/connections).
💡 Exam Tip: A try block MUST be followed by at least one catch OR a finally block (can't have try alone). Multiple catch blocks are allowed to handle different exception types separately, evaluated top-to-bottom.
3. Difference Between throw and throws
| Feature | throw | throws |
| Purpose | Actually THROWS/triggers an exception instance | DECLARES that a method might throw certain exceptions |
| Used with | A single exception OBJECT | Exception CLASS name(s), comma-separated if multiple |
| Location | Inside a method body | In the method SIGNATURE (declaration line) |
| Syntax | throw new ExceptionType("message"); | void method() throws ExceptionType { } |
| Number allowed | Only ONE exception object per throw statement | MULTIPLE exceptions can be declared, comma-separated |
Worked Example — Both Together:
import java.io.*;
class Main {
// "throws" — declares this method MIGHT throw these exceptions
static void readFile(String filename) throws FileNotFoundException, IOException {
if (filename == null) {
// "throw" — actually throwing ONE specific exception object
throw new IllegalArgumentException("Filename cannot be null");
}
FileReader fr = new FileReader(filename); // may throw FileNotFoundException
// ... reading logic that may throw IOException
}
public static void main(String[] args) {
try {
readFile(null);
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
// Output:
Caught: Filename cannot be null
✅ Real-world Analogy:
throws = a warning sign on a door: "Caution: this room may have obstacles" (declaration, no action yet)
throw = actually placing an obstacle right there (the real action/event)
💡 Exam Tip: throws is a DECLARATION (compiler-facing, tells callers "be prepared to handle this"); throw is the actual ACTION statement that creates and triggers the exception at runtime. This differentiation with example code is a confirmed PYQ pattern.
4. Types of Exceptions — Checked & Unchecked
📖 Checked Exception: Exceptions checked/verified by the COMPILER at compile time — the programmer is FORCED to either handle it (try-catch) or declare it (throws), otherwise the code won't compile.
📖 Unchecked Exception: NOT checked by the compiler — occur at RUNTIME, handling is optional (though recommended). All subclasses of RuntimeException.
| Feature | Checked | Unchecked |
| Checked by | Compiler (compile-time) | JVM (run-time only) |
| Must handle? | YES — mandatory (try-catch or throws) | NO — optional |
| Parent class | Exception (excluding RuntimeException) | RuntimeException |
| Examples | IOException, SQLException, FileNotFoundException | ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException |
| Typical cause | External factors (file not found, DB connection failed) | Programming logic errors/bugs |
// CHECKED exception - compiler FORCES handling
import java.io.*;
void readFile() throws IOException { // must declare, or code won't compile
FileReader fr = new FileReader("data.txt");
}
// UNCHECKED exception - compiler does NOT force handling
void divide(int a, int b) {
System.out.println(a / b); // ArithmeticException possible if b=0
// no try-catch or throws REQUIRED - compiles fine either way
}
💡 Exam Tip: The quickest test: "Does the compiler give an error if I DON'T handle it?" → YES = Checked. → NO = Unchecked. All Unchecked exceptions are subclasses of RuntimeException — memorize this class relationship.
5. Exception Handling in Java
📖 Exception Handling: The mechanism of responding to exceptions in a controlled way — preventing abrupt program termination and allowing graceful recovery or a clean error message.
Why Catching Exceptions is Recommended:
✅ 1. Prevents Abnormal Termination: Without catching, an exception crashes the ENTIRE program immediately — even parts of the code that had nothing to do with the error never get to run.
✅ 2. Better User Experience: Instead of a raw, technical stack-trace crash, the program can show a friendly, meaningful error message.
✅ 3. Resource Cleanup: Using try-catch-finally ensures resources (files, database connections) are properly closed even when something goes wrong.
✅ 4. Program Continuity: The rest of the program can continue running normally after handling the error, instead of stopping completely.
// WITHOUT exception handling — program CRASHES
public class Main {
public static void main(String[] args) {
int result = 10 / 0; // ❌ crashes here
System.out.println("Never reached");
}
}
// WITH exception handling — program CONTINUES gracefully
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues normally"); // ✅ this DOES run
}
}
💡 Exam Tip: "Why catching exceptions is recommended" answers should emphasize CONTROL — without handling, ONE error anywhere kills the WHOLE program; with handling, the program stays in control and can decide exactly how to respond and continue.
⚡
Ready for Exam?
Sab padh liya? Ab Quick Revision karo — code, key points aur PYQ answers ek jagah!
Quick Revision Karo →
⚡
Quick Revision — Last Minute Exam Prep!
📌 How to Use: Read this 5-10 minutes before exam. Contains all important points in condensed form. Focus on tables, comparisons, and key formulas!
☕ Chapter 1.1 — Java Fundamentals
📖 Java: Platform-independent (bytecode+JVM), OOP, no pointers, auto Garbage Collection.
🔑 C++ vs Java — Top 3 Differences:
1. Platform: native code vs bytecode+JVM
2. Pointers: explicit vs hidden (references)
3. Multiple Inheritance: classes(C++) vs Interfaces only(Java)
ACCESS SPECIFIERS (most→least restrictive):
private (class only) → default (package) → protected (package+subclass) → public (everywhere)
| Topic | Key Fact | Trick |
| Tokens | Keywords, Identifiers, Literals, Operators, Separators | true/false/null are literals, NOT keywords |
| Data Types | 8 primitives + Non-primitive | char=2 bytes(Unicode), not 1 like C/C++ |
| Access Specifiers | 4 levels | private=most restrictive, public=least |
🔗 Chapter 1.2 — OOPS using Java
📖 "new" Keyword (PYQ!): 1) Allocates memory on heap, 2) Calls constructor, 3) Returns reference — stored in a variable.
🔑 Class vs Object:
Class = Blueprint (no memory) | Object = Instance (memory on heap, created via "new")
OVERLOADING vs OVERRIDING:
Overloading = SAME class, different params, compile-time
Overriding = PARENT-CHILD, same signature, run-time
✅ Static vs Non-Static (PYQ — Memory Management!):
Static → Method Area, ONE copy shared by all objects
Non-Static → Heap, ONE separate copy PER object
💡 Multiple Inheritance via Interfaces (PYQ!):
class Duck implements Flyable, Swimmable { ... }
No Diamond Problem — implementing class provides ONE implementation, no ambiguity.
| Topic | Key Fact | Trick |
| Inheritance | extends keyword | Multiple NOT allowed via classes (Diamond Problem) |
| Abstraction | Abstract class(partial) vs Interface(full) | Abstract class can't be instantiated |
| Polymorphism | Overload=compile-time, Override=runtime | Parent ref + Child object = classic runtime example |
| Encapsulation | private fields + public getter/setter | Different from Abstraction (data vs implementation hiding) |
🛡️ Chapter 1.3 — Exception Handling
📖 Error vs Exception: Both extend Throwable. Error=unrecoverable(OutOfMemoryError). Exception=recoverable(ArithmeticException).
🔑 throw vs throws (PYQ!):
throw → actually throws ONE exception object, INSIDE method body
throws → DECLARES possible exceptions, in method SIGNATURE, multiple allowed
Analogy: throws=warning sign on door, throw=actually placing the obstacle
CHECKED vs UNCHECKED (PYQ!):
Checked → compiler FORCES handling (IOException, SQLException)
Unchecked → RuntimeException subclasses, handling optional (ArithmeticException, NullPointerException)
✅ Why Catch Exceptions? (PYQ!):
Prevents crash, better UX, resource cleanup, program continuity — one uncaught error kills the WHOLE program otherwise.
| Topic | Key Fact | Trick |
| try/catch/throw | Risky code / Handle it / Trigger manually | try needs catch OR finally |
| throw vs throws | Action vs Declaration | throw=1 object, throws=multiple classes |
| Checked vs Unchecked | Compile-time vs Runtime check | Unchecked = RuntimeException subclass |
⚠️ Common Exam Mistakes
❌ Confusing throw (action, one object) with throws (declaration, multiple classes)
❌ Forgetting Checked exceptions are compiler-FORCED, Unchecked are not
❌ Saying Java "supports multiple inheritance" without clarifying it's ONLY via interfaces, not classes
❌ Confusing Overloading (same class, different params) with Overriding (parent-child, same signature)
❌ Forgetting static members live in Method Area (ONE copy) while non-static live in Heap (one PER object)
❌ Mixing up Encapsulation (hiding DATA) with Abstraction (hiding IMPLEMENTATION)
❌ Writing "new" only allocates memory — forgetting it ALSO calls the constructor and returns a reference
❌ Forgetting char is 2 bytes (Unicode) in Java, not 1 byte like C/C++
✅ Pre-Exam Checklist
☑ Java features + platform independence (bytecode+JVM)
☑ C++ vs Java — top differences (platform, pointers, multiple inheritance)
☑ Keywords vs Tokens vs Identifiers vs Literals
☑ 8 primitive data types + sizes
☑ public/private/protected/default access levels
☑ Class vs Object + purpose of "new" keyword
☑ Inheritance types + why multiple class inheritance isn't allowed
☑ Abstraction — abstract class vs interface
☑ Polymorphism — overloading vs overriding with code
☑ Encapsulation — private fields + getters/setters
☑ Static vs Non-static — memory management (Method Area vs Heap)
☑ Multiple inheritance via interfaces — full worked code example
☑ Error vs Exception hierarchy (Throwable)
☑ try/catch/throw usage with code
☑ throw vs throws — differences + example code
☑ Checked vs Unchecked exceptions + examples
☑ Why catching exceptions is recommended (4 reasons)
🎯 Exam Strategy
2 Mark Questions:
• Direct definition + 1 example. Time: 3-4 minutes.
• "Differentiate" → always draw a 2-column table.
5 Mark Questions:
• "Demonstrate/Implement" questions — ALWAYS write complete, working Java code, not just pseudocode.
• "Differentiate with example code" — show the table AND a code snippet, not just one or the other.
• Time: 7-8 minutes per question.
Marks-saving tip:
Even if the full program doesn't compile perfectly in your head, writing correct Java SYNTAX (proper class structure, correct keyword usage) earns partial marks — examiners check structure and concept understanding, not just a working compiler output.
🌟 All the Best!
Java is practice-based — don't just read, write code! throw vs throws, static vs non-static, aur multiple inheritance via interfaces practice karo with real code examples. Tu ready hai! 💪☕
📄
Previous Year Questions
📌 Source: Mid Semester Test-1 (MST-1), Academic Year 2025-2026 — Unit 1 only. Maximum Marks: 20, Time: 1 Hour.
Section A (5 × 2 = 10 marks)
2M
MST-1
State the purpose of the "new" keyword in Java.
▼
The "new" keyword does 3 things: 1) Allocates MEMORY on the heap for a new object, 2) Calls the class's CONSTRUCTOR to initialize the object, 3) Returns a REFERENCE to that object, stored in a variable. Without "new", a declared variable (e.g. Student s1;) points to nothing (null) — no object actually exists yet.
2M
MST-1
Compare a class and an object with differences and examples.
▼
Class: A blueprint/template — no memory allocated. Example: class Student { String name; }
Object: An actual instance with real memory (on heap), created via "new". Example: Student s1 = new Student();
Key differences: Class defines structure (declared once); Object holds actual data (many can be created). See Chapter 1.2, Section 1 for the full comparison table.
2M
MST-1
Explain memory management for static vs. non-static members in Java.
▼
Static members: Stored in the Method Area (Class Area) — allocated ONCE when the class is loaded, and shared by ALL objects (only one copy exists).
Non-static (instance) members: Stored in the Heap — a SEPARATE copy is allocated for EVERY object created via "new". If 1000 objects are created, there are 1000 separate copies of each instance field.
2M
MST-1
Define checked and unchecked exceptions.
▼
Checked Exception: Verified by the compiler at compile-time — MUST be handled (try-catch) or declared (throws), or the code won't compile. Example: IOException.
Unchecked Exception: NOT checked by the compiler — occurs at runtime, handling is optional. All are subclasses of RuntimeException. Example: ArithmeticException.
2M
MST-1
Explain why catching exceptions is recommended in Java.
▼
Catching exceptions is recommended because it: 1) Prevents abrupt/abnormal program termination, 2) Provides a better user experience with meaningful error messages instead of raw stack traces, 3) Allows proper resource cleanup (files/connections) via finally blocks, 4) Lets the program continue running normally after handling the error, instead of crashing completely.
Section B (2 × 5 = 10 marks)
5M
MST-1
Demonstrate how Java supports multiple inheritance using interfaces by implementing a Java program that involves two interfaces and a class. Apply the concept to show why interfaces are preferred over multiple class inheritance in Java.
▼
Why Java disallows multiple CLASS inheritance:
The "Diamond Problem" — if class C extends both class A and class B, and BOTH have a method with the same name but different implementations, the compiler cannot decide which version C should inherit, creating ambiguity.
Working Code — Multiple Inheritance via 2 Interfaces:
interface Flyable {
void fly();
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
public void fly() {
System.out.println("Duck flies short distances");
}
public void swim() {
System.out.println("Duck swims well");
}
}
public class Main {
public static void main(String[] args) {
Duck d = new Duck();
d.fly();
d.swim();
}
}
// Output:
Duck flies short distances
Duck swims well
Why Interfaces are Preferred over Multiple Class Inheritance:
1.
No Diamond Problem: Since interfaces (traditionally) only declare method signatures with no implementation, there's nothing conflicting to inherit — the implementing class provides ONE single implementation.
2.
Flexible design: A class can implement any number of interfaces, gaining multiple "contracts" without inheriting conflicting concrete behavior.
3.
Loose coupling: Interfaces define WHAT a class can do, not HOW — keeping the design cleaner and more maintainable than deep multiple-inheritance class hierarchies.
5M
MST-1
Differentiate between throw and throws with example code.
▼
Key Differences:
| Feature | throw | throws |
| Purpose | Actually throws an exception object | Declares possible exceptions |
| Used with | A single exception OBJECT | Exception CLASS name(s) |
| Location | Inside method body | In method signature |
| Count | Only ONE per statement | Multiple allowed, comma-separated |
Example Code (both together):
import java.io.*;
class Main {
// "throws" - declares this method MIGHT throw these
static void readFile(String filename) throws FileNotFoundException, IOException {
if (filename == null) {
// "throw" - actually throwing ONE exception object
throw new IllegalArgumentException("Filename cannot be null");
}
FileReader fr = new FileReader(filename);
}
public static void main(String[] args) {
try {
readFile(null);
} catch (Exception e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
// Output:
Caught: Filename cannot be null
Real-world Analogy:
•
throws: Sign on door saying "Beware: Area may have obstacles"
•
throw: Actually placing an obstacle on the path
Key Point: throws is a warning/declaration,
throw is the actual action of throwing an exception.