📖 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
💡 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.
The bytecode is the same everywhere. Only the JVM is different for each operating system.
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).
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.
💡 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.
Static block and a complete example
A static block runs once, when the class is loaded, before main(). It is used to initialise static data.
public class StaticDemo {
static int count = 0; // shared by ALL objects (one copy in class memory)
static String college = "CU"; // common data
String name; // each object has its own copy
static { // static block: runs once when the class loads
System.out.println("Static block executed");
}
StaticDemo(String name) {
this.name = name;
count++; // every new object increases the shared counter
}
static void showCount() { // static method: call without creating an object
System.out.println("Objects created: " + count + " (college = " + college + ")");
}
public static void main(String[] args) {
new StaticDemo("Amit");
new StaticDemo("Neha");
new StaticDemo("Raj");
StaticDemo.showCount(); // called with the class name
}
}
📖 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
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)
💡 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.
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.
Exception class hierarchy
Checked exceptions are checked by the compiler. Unchecked ones (RuntimeException and its children, and Error) are not.
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!
🎨 Visual Quick Recall
1. static keyword
📖 Definition: static members belong to the class, not to objects. One shared copy.
💡 Example: static int count counts all objects created.
📌 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)
📖 "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
✅ 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
📌 Paper 1 — In Semester Test-1, Academic Year 2026-2027 — Unit 1 only. Subject: Project Based Learning in Java (24CSH-301 / 24ITH-301), BE(CSE/IT), Semester 5. Maximum Marks: 20, Time: 1 Hour.
Section A (5 × 2 = 10 marks)
2M2026-27
Q1. Explain the role of the static keyword in Java and provide an example demonstrating its usage. [CO1 | BT2]▼
Answer:
The static keyword makes a member belong to the class instead of any single object. There is only one shared copy, created when the class is loaded, and it can be used with the class name without creating an object.
Static member
Role
Example
Variable
One shared copy for all objects
static int count
Method
Called without an object. Can use only static members directly (no this)
static void showCount()
Block
Runs once when the class is loaded, to initialise static data
static { … }
Nested class
A class inside another class that needs no outer object
static class Helper
public class StaticDemo {
static int count = 0; // shared by ALL objects (one copy in class memory)
static String college = "CU"; // common data
String name; // each object has its own copy
static { // static block: runs once when the class loads
System.out.println("Static block executed");
}
StaticDemo(String name) {
this.name = name;
count++; // every new object increases the shared counter
}
static void showCount() { // static method: call without creating an object
System.out.println("Objects created: " + count + " (college = " + college + ")");
}
public static void main(String[] args) {
new StaticDemo("Amit");
new StaticDemo("Neha");
new StaticDemo("Raj");
StaticDemo.showCount(); // called with the class name
}
}
Why is main() static? The JVM must call it before any object exists. Each object has its own name, but all share one count and college.
2M2026-27
Q2. Discuss when it is appropriate to use the protected access modifier in Java classes. [CO1 | BT2]▼
Answer:
protected allows access inside the same package and in subclasses, even when the subclass is in a different package. Code that is neither in the package nor a subclass cannot use it.
Use protected when: 1) a member is meant to be reused or overridden by subclasses (for example a base-class helper method or a value like speed), 2) you are designing a base class for inheritance, but do not want the whole world to touch it, 3) it sits between private (too strict for subclasses) and public (too open).
Modifier
Same class
Same package
Subclass (other package)
Everywhere else
private
✅
❌
❌
❌
default (no keyword)
✅
✅
❌
❌
protected
✅
✅
✅
❌
public
✅
✅
✅
✅
package a;
public class Vehicle {
protected int speed = 60; // visible to subclasses, even in other packages
protected void show() { System.out.println("Speed = " + speed); }
}
package b;
import a.Vehicle;
public class Car extends Vehicle { // subclass in a different package
public static void main(String[] args) {
Car c = new Car();
c.speed = 80; // OK: protected member used through inheritance
c.show(); // OK
}
}
// Output
Speed = 80
Not allowed: a non-subclass in another package that writes v.speed gets the compile error "speed has protected access in Vehicle".
Prefer private fields with getters. Use protected only for what subclasses really need.
2M2026-27
Q3. Explain how does Java achieve platform independence. [CO1 | BT2]▼
Answer:
Platform independence means the same Java program runs on any operating system without changes. Java achieves it with bytecode and the JVM (Write Once, Run Anywhere).
The bytecode is the same everywhere. Only the JVM is different for each operating system.
javac compiles the source file into bytecode (.class), not into machine code for one CPU
Each OS has its own JVM, which understands the same bytecode and runs it on that machine (the JIT compiler turns hot bytecode into native code)
Java also fixes the size of data types (an int is always 32 bits), so results do not depend on the machine
Java programs are platform independent, but the JVM itself is platform dependent.
2M2026-27
Q4. Discuss the role of interfaces in achieving multiple inheritance in Java. [CO2 | BT2]▼
Answer:
Why not classes? If a class could extend two classes that have the same method, Java would not know which one to run (the diamond problem). So Java allows only one parent class. Interfaces solve it: an interface only declares what to do (a contract) and has no instance state. A class can implement many interfaces, so it gets multiple inheritance of type and behaviour safely.
interface Printable { void print(); }
interface Scannable { void scan(); }
class MultiFunctionDevice implements Printable, Scannable { // two interfaces, one class
public void print() { System.out.println("Printing document..."); }
public void scan() { System.out.println("Scanning document..."); }
}
public class Printable_Main {
public static void main(String[] args) {
MultiFunctionDevice d = new MultiFunctionDevice();
d.print();
d.scan();
Scannable s = d; // the same object can be used as either type
s.scan();
}
}
Same default method in two interfaces? The class must override it and choose:
interface A { default void hello() { System.out.println("Hello from A"); } }
interface B { default void hello() { System.out.println("Hello from B"); } }
class C implements A, B {
public void hello() { // must override to remove the ambiguity
A.super.hello(); // choose which interface's version to use
}
}
public class DefaultConflict {
public static void main(String[] args) { new C().hello(); }
}
// Output
Hello from A
2M2026-27
Q5. Define throw and throws keywords. [CO3 | BT1]▼
Answer:
throw is a statement used inside a method to create and throw one exception object: throw new IllegalArgumentException("msg"); throws is a keyword written in the method signature to declare which checked exceptions the method may pass on to its caller.
throw
throws
Where
Inside the method body
In the method declaration
Followed by
One exception object
One or more exception class names
Purpose
Actually throws the exception
Warns the caller to handle it
Example
throw new IOException();
void read() throws IOException
import java.io.IOException;
public class ThrowThrowsDemo {
static void checkAge(int age) { // throw: used INSIDE the method body
if (age < 18) throw new IllegalArgumentException("Age must be 18 or above");
System.out.println("Eligible to vote");
}
static void readFile() throws IOException { // throws: written in the method SIGNATURE
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
checkAge(20);
checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
try {
readFile(); // caller must handle or declare IOException
} catch (IOException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
// Output
Eligible to vote
Caught: Age must be 18 or above
Caught: File not found
Section B (2 × 5 = 10 marks)
5M2026-27
Q6. Implement an abstract class Product with an abstract method calculateDiscount(). Create subclasses Electronics, Clothing, and Furniture. Override the method to calculate discounts according to product category. Display product information and final price after discount. [CO2 | BT3]▼
Answer:
Abstract class: a class that cannot be instantiated and may contain abstract methods (no body). Subclasses must override them. Here Product keeps the common data and logic, and each category supplies its own discount.
Abstraction: Product defines what must be done (calculateDiscount), subclasses define how
Inheritance: Electronics, Clothing and Furniture extend Product and call super(name, price)
Overriding + runtime polymorphism: a Product reference calls the correct subclass method
Q7. Classify the exception class hierarchy in Java and provide a program to illustrate the handling of unchecked exceptions, discussing the significance and potential scenarios where unchecked exceptions may arise. [CO3 | BT4]▼
Answer:
Exception hierarchy: every problem is an object of a class under Throwable. It has two branches: Error (serious JVM problems, not meant to be caught) and Exception (problems the program can handle).
Checked exceptions are checked by the compiler. Unchecked ones (RuntimeException and its children, and Error) are not.
// Output
1) ArithmeticException: / by zero
2) ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
3) NullPointerException: text is null
4) NumberFormatException: For input string: "12abc"
finally block always runs
Program continues normally
Significance of unchecked exceptions: they signal programming mistakes (bad input, null, wrong index). The compiler does not force try-catch, so code stays clean. The real fix is to validate first, and catch only where the program can recover.
Scenario
Unchecked exception
Dividing by zero
ArithmeticException
Using a null reference
NullPointerException
Index outside an array
ArrayIndexOutOfBoundsException
Converting text like "12abc" to a number
NumberFormatException
Wrong type cast
ClassCastException
Passing an invalid argument
IllegalArgumentException
📌 Paper 2 — 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)
2M2025-26
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.
2M2025-26
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.
2M2025-26
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.
2M2025-26
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.
2M2025-26
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)
5M2025-26
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.
5M2025-26
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.