0% found this document useful (0 votes)
2 views29 pages

Core Java Complete Notes 1

Core Java Notes provide a comprehensive syllabus covering essential topics from Java basics to advanced features, including OOP, exception handling, multithreading, and collections. Each section is designed to simplify complex concepts with real examples and code snippets, making it suitable for beginners and those preparing for interviews. The document also includes a section on top interview questions and answers to aid in preparation.

Uploaded by

Chirag Verma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Core Java Complete Notes 1

Core Java Notes provide a comprehensive syllabus covering essential topics from Java basics to advanced features, including OOP, exception handling, multithreading, and collections. Each section is designed to simplify complex concepts with real examples and code snippets, making it suitable for beginners and those preparing for interviews. The document also includes a section on top interview questions and answers to aid in preparation.

Uploaded by

Chirag Verma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Core Java Notes

Complete Syllabus — Tokens to Collections


Tokens • OOP • Inheritance • Polymorphism • Interfaces
Exception Handling • Collections • Multithreading • Java 8+
Every topic explained simply with real examples & code
Core Java Notes — Complete Syllabus Beginner to Interview Ready

Table of Contents
PART A — JAVA BASICS
1. Tokens
2. Keywords
3. Identifiers
4. Data Types & 5. Primitive Types
6. Casting

PART B — OBJECT ORIENTED PROGRAMMING (OOP)


7. Classes & Objects
8. The 'new' Keyword
9. Variables in Java
10. Methods
11. Memory Structure — Stack & Heap
12. Static and Non-Static Members
13. Variable Shadowing
14. The 'this' Keyword
15. Constructors
16. Inheritance
17. super Keyword / this vs super
18. Non-Primitive Types
19. Upcasting & Downcasting
20. Polymorphism
21. Variable Hiding
22. Method Overloading vs Overriding
23. Encapsulation
24. Abstraction
25. Abstract Class
26. Interface
27. Has-A Relationship
28. Packages
29. Access Modifiers
30. final Keyword
31. Singleton Class
32. Immutable Class
33. Object Class
34. Wrapper Classes

PART C — JAVA 8+ FEATURES


35. Lambda Expressions
36. Stream API
37. Time & Date API

PART D — EXCEPTION HANDLING


38. try / catch / finally / throw / throws

PART E — FILE HANDLING

Core Java Notes | Study Guide Page 2


Core Java Notes — Complete Syllabus Beginner to Interview Ready

39. File Handling

PART F — MULTITHREADING
40. Multithreading

PART G — COLLECTIONS FRAMEWORK


41. Collections Framework

PART H — INTERVIEW Q&A;


42. Top 20 Interview Questions & Answers

Core Java Notes | Study Guide Page 3


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part A — Java Basics

1. Tokens
A token is the smallest unit in a Java program that the compiler can understand. When Java reads your source
code, it first breaks it down into tokens — just like breaking a sentence into individual words. Every element you
write belongs to one of five categories:

Token Type Description Example

Keywords Reserved words with a fixed meaning int, class, if, return

Identifiers Names given by the programmer myVar, Car, calcArea()

Literals Fixed constant values in code 42, 3.14, 'A', "Hi", true

Operators Symbols that perform operations +, -, *, /, ==, &&, ||

Separators Symbols that structure code {}()[];,.

public class TokenDemo { // 'public','class' = Keywords public static void main(String[] args) {
int number = 42; // 'int'=Keyword | 'number'=Identifier | '42'=Literal int result = number + 10;
// '+'=Operator | ';'=Separator [Link](result); } }

Real-world analogy: Tokens are to Java code what words are to a sentence. Just as sentences have nouns,
verbs, and punctuation — Java programs have keywords, identifiers, operators, literals, and separators.

2. Keywords
Keywords are reserved words that Java has already assigned a special meaning. You cannot use them as
variable/class/method names. Java has 53 reserved keywords. Here are the most important ones grouped by
category:

Category Keywords

Data Types byte, short, int, long, float, double, char, boolean, void

Access Modifiers public, private, protected

Class & Object class, interface, extends, implements, abstract, new, this, super, instanceof, enum

Control Flow if, else, switch, case, default, for, while, do, break, continue, return

Exception Handling try, catch, finally, throw, throws

Modifiers & Others static, final, synchronized, volatile, transient, import, package, assert, native

Important: Keywords are always in lowercase. Java is case-sensitive, so 'Int' is NOT a keyword — only 'int'
is. Also, true, false, and null are technically literals but also reserved — you cannot use them as identifiers.

3. Identifiers

Core Java Notes | Study Guide Page 4


Core Java Notes — Complete Syllabus Beginner to Interview Ready

An identifier is any name YOU give to a variable, class, method, or interface. Java has strict rules:
• Can contain: letters (a–z, A–Z), digits (0–9), underscore (_), dollar sign ($)
• Cannot start with a digit — '2name' is invalid; 'name2' is valid
• Cannot be a Java keyword — you cannot name a variable 'int' or 'class'
• No spaces or special characters (@, #, !, etc.)
• Case-sensitive — 'Age', 'age', and 'AGE' are three different identifiers

What Convention Example

Variables/Methods camelCase — start lowercase studentAge, calculateArea()

Classes/Interfaces PascalCase — start uppercase StudentDetails, Runnable

Constants (final) ALL_CAPS with underscore MAX_SIZE, PI_VALUE

Packages all lowercase with dots [Link]

4. Data Types
A data type tells Java what kind of value a variable stores and how much memory to allocate. Java is strongly
typed — every variable must be declared with a type. Data types fall into two broad groups:
• Primitive — 8 built-in types. Values stored directly in stack memory.
• Non-Primitive (Reference) — Objects, Arrays, Strings. Variable stores a reference (address) to heap
memory.

Category Description & Examples

Primitive byte, short, int, long, float, double, char, boolean — store values directly

Non-Primitive String, Arrays, Classes, Interfaces, Enums — store a memory reference

5. Primitive Types — All 8 in Detail


Type Size Default Value Use For

byte 1 byte 0 Small numbers (-128 to 127). Saving memory in large arrays.

short 2 bytes 0 Medium numbers (-32,768 to 32,767).

int 4 bytes 0 Most whole numbers. Default integer type. (~±2.1 billion)

long 8 bytes 0L Very large whole numbers. Add 'L' suffix. Use for timestamps.

float 4 bytes 0.0f Decimal numbers, less precise. Add 'f' suffix. (~6-7 digits)

double 8 bytes 0.0 Decimal numbers, more precise. Default decimal type. (~15 digits)

char 2 bytes '\u0000' Single Unicode character enclosed in single quotes: 'A', '5'.

boolean 1 bit false Only two values: true or false. Used in conditions.

// Declaring each primitive type byte b = 100; short sh = 30_000; int i = 1_000_000; //
underscores allowed for readability long l = 9_999_999_999L; // must end with 'L' float f =
3.14f; // must end with 'f' double d = 3.14159265358; // default decimal char c = 'A'; // single
quotes boolean ok = true; // Checking sizes at runtime [Link](Integer.MAX_VALUE);

Core Java Notes | Study Guide Page 5


Core Java Notes — Complete Syllabus Beginner to Interview Ready

// 2147483647 [Link](Double.MIN_VALUE); // 4.9E-324

6. Casting — Type Conversion


Type casting converts a value from one data type to another. There are two kinds based on direction:

Kind Explanation

Widening (Implicit/Automatic) Smaller → Larger type. No data loss. Java handles it automatically. Order: byte →
short → int → long → float → double

Narrowing (Explicit/Manual) Larger → Smaller type. Data may be lost. You must write the target type in
parentheses: (int) myDouble. The decimal part is DROPPED (not rounded).

// WIDENING — automatic, no syntax needed int myInt = 9; double myDouble = myInt; // int →
double, auto [Link](myDouble); // 9.0 // NARROWING — must cast explicitly double
price = 9.99; int intPrice = (int) price; // double → int, manual [Link](intPrice);
// 9 (NOT 10 — decimal is CUT, not rounded) // Char ↔ int char letter = 'A'; int ascii =
letter; // widening: char → int [Link](ascii); // 65 (ASCII value of 'A') char back
= (char) 66; // narrowing: int → char [Link](back); // B

Warning: Casting 300 into a byte gives -56, NOT 300, because byte max is 127. Always verify the value fits in
the target type before narrowing.

Core Java Notes | Study Guide Page 6


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part B — Object Oriented Programming (OOP)

7. Classes and Objects


A class is a blueprint/template that defines the attributes (data) and behaviours (methods) that objects of that
type will have. An object is a real instance created from that blueprint. Think of a class as an architectural
drawing and objects as the actual buildings.
// CLASS — the blueprint public class Student { String name; // attribute / field int age;
double marks; void study() { [Link](name + " is studying."); } void displayInfo() {
[Link]("Name: "+name+", Age: "+age+", Marks: "+marks); } } // Creating and using
OBJECTS public class Main { public static void main(String[] args) { Student s1 = new Student();
// create object 1 [Link] = "Alice"; [Link] = 20; [Link] = 92.5; [Link](); // Name:
Alice, Age: 20, Marks: 92.5 Student s2 = new Student(); // create object 2 — independent [Link]
= "Bob"; [Link] = 22; [Link] = 78.0; [Link](); // Name: Bob, Age: 22, Marks: 78.0 } }

Key point: s1 and s2 share the same structure but hold completely independent data. Changing [Link]
does NOT affect [Link].

8. The 'new' Keyword


The new keyword creates an object. When you write new ClassName(), Java: (1) allocates memory in the
heap, (2) initialises fields to defaults, (3) calls the constructor. The variable (reference) lives on the stack.
Car myCar = new Car(); // 'myCar' on STACK holds the address → Car object in HEAP Car
anotherRef = myCar; // both point to the SAME heap object [Link] = 200;
[Link]([Link]); // 200 — same object!

9. Variables in Java
Java has three variable types based on where they are declared:

Type Where Declared Key Points

Instance Variable Inside class, outside Each object gets its own copy. Default value given. Stored in heap.
methods

Static Variable Inside class with 'static' ONE shared copy for ALL objects. Lives as long as program runs.

Local Variable Inside a method or block Must be initialised before use (no default). Stored in stack. Destroyed
when method ends.

public class VariableDemo { int instanceVar = 10; // Instance — each object gets own copy static
int staticVar = 100; // Static — shared across ALL objects void show() { int localVar = 50; //
Local — only lives inside this method [Link](instanceVar + " " + staticVar + " " +
localVar); } public static void main(String[] args) { VariableDemo obj1 = new VariableDemo();
VariableDemo obj2 = new VariableDemo(); [Link] = 20;
[Link]([Link]); // 20 [Link]([Link]); // 10 —
unaffected [Link] = 999; [Link]([Link]); // 999 — shared!
[Link]([Link]); // 999 — shared! } }

10. Methods

Core Java Notes | Study Guide Page 7


Core Java Notes — Complete Syllabus Beginner to Interview Ready

A method is a named block of code that performs a task and can be reused. Syntax: accessModifier
returnType methodName(parameters) { body }
// No parameters, no return void greet() { [Link]("Hello!"); } // Parameters and a
return value int add(int a, int b) { return a + b; } // Multiple parameters String
fullName(String first, String last) { return first + " " + last; } // Varargs — variable number
of arguments int sumAll(int... nums) { int total = 0; for (int n : nums) total += n; return
total; } [Link](sumAll(1, 2, 3, 4, 5)); // 15 // Pass-by-VALUE for primitives (copy
is passed, original unchanged) void changeInt(int x) { x = 999; } int n = 10; changeInt(n);
[Link](n); // still 10 // Pass-by-REFERENCE for objects (the address is copied —
object CAN be modified) void changeName(Student s) { [Link] = "Changed"; }

11. Memory Structure — Stack and Heap


Feature Stack Memory Heap Memory

Stores Local variables, method call frames, Objects and instance variables
references

Management Automatic (LIFO — Last In First Out) Garbage Collector cleans unused objects

Speed Very fast Slightly slower

Thread Each thread has its own private stack Shared among ALL threads

Full error StackOverflowError OutOfMemoryError

void calculate() { int x = 5; // 'x' on STACK Student s = new Student(); // reference 's' on
STACK // actual Student object in HEAP [Link] = "Alice"; // 'name' stored in HEAP (inside the
object) } // When calculate() ends: x and s removed from stack // Student object stays in HEAP
until GC collects it

12. Static and Non-Static Members


Aspect static Member

Belongs to The CLASS itself — shared by all objects

Access [Link] — no object needed

Variables ONE copy shared across all objects

Methods Cannot access instance (non-static) variables directly

Block Runs ONCE when class is first loaded into memory

Non-static access Non-static methods CAN access both static and instance members

public class BankAccount { static int totalAccounts = 0; // shared counter String owner; int
balance; // per-object data static { [Link]("Class loaded"); } // static block
BankAccount(String owner, int balance) { [Link] = owner; [Link] = balance;
totalAccounts++; // update shared counter } static void showTotal() { // static method — no
object needed [Link]("Total accounts: " + totalAccounts); } void showBalance() { //
instance method — needs object [Link](owner + ": " + balance); } } BankAccount a1 =
new BankAccount("Alice", 5000); BankAccount a2 = new BankAccount("Bob", 3000);
[Link](); // Total accounts: 2 [Link](); // Alice: 5000

Core Java Notes | Study Guide Page 8


Core Java Notes — Complete Syllabus Beginner to Interview Ready

13. Variable Shadowing


Variable shadowing occurs when a local variable or parameter has the same name as an instance variable.
The local one 'shadows' (hides) the instance variable within that scope. Use [Link] to reach the instance
variable.
public class Person { String name = "Instance"; // instance variable void setName(String name) {
// parameter 'name' shadows instance variable [Link](name); // "Alice" — the
parameter [Link]([Link]); // "Instance" — the instance variable [Link] =
name; // correct assignment } }

14. The 'this' Keyword


The this keyword refers to the current object. It has 4 uses:

Use Explanation

[Link] Distinguish instance variable from parameter with the same name

[Link]() Call another method in the same class explicitly

this(...) Constructor chaining — call another constructor of the same class. MUST be first line.

return this Return the current object — enables method chaining (builder pattern)

public class Rectangle { double width, height; Rectangle(double width, double height) {
[Link] = width; [Link] = height; // use 1: resolve shadowing } Rectangle() { this(1.0,
1.0); } // use 3: constructor chaining Rectangle setWidth(double w) { [Link] = w; return
this; } // use 4 Rectangle setHeight(double h) { [Link] = h; return this; } // use 4 double
area() { return [Link] * [Link]; } // use 2 } // Method chaining double a = new
Rectangle().setWidth(5).setHeight(3).area(); // 15.0

15. Constructors
A constructor is automatically called when you create an object with new. It initialises the object. Rules: same
name as class, no return type, can be overloaded (multiple constructors), if none is written Java provides a
default one.
public class Employee { String name; int id; double salary; // Default constructor Employee() {
name = "Unknown"; id = 0; salary = 0.0; } // Parameterised constructor Employee(String name, int
id, double salary) { [Link] = name; [Link] = id; [Link] = salary; } // Copy constructor
Employee(Employee other) { [Link] = [Link]; [Link] = [Link]; [Link] =
[Link]; } void display() { [Link]("ID:"+id+" Name:"+name+" Salary:"+salary);
} } Employee e1 = new Employee(); Employee e2 = new Employee("Alice", 101, 75000.0); Employee e3
= new Employee(e2); // independent copy [Link](); // ID:0 Name:Unknown Salary:0.0
[Link](); // ID:101 Name:Alice Salary:75000.0 [Link](); // ID:101 Name:Alice
Salary:75000.0

Core Java Notes | Study Guide Page 9


Core Java Notes — Complete Syllabus Beginner to Interview Ready

16. Inheritance
Inheritance lets a child class acquire properties and behaviours of a parent class using the extends keyword. It
models an IS-A relationship and promotes code reuse. Java supports only single class inheritance but multiple
interface implementation.

Type Description Supported in Java

Single Child extends one parent YES

Multilevel A extends B, B extends C (chain) YES

Hierarchical Multiple children extend one parent YES

Multiple One child extends two parent classes NO (use interfaces)

Hybrid Combination of above types Partially via interfaces

class Vehicle { String brand; int speed; Vehicle(String brand, int speed) { [Link]=brand;
[Link]=speed; } void start() { [Link](brand + " started"); } } class Car extends
Vehicle { // IS-A Vehicle int doors; Car(String brand, int speed, int doors) { super(brand,
speed); // call parent constructor [Link] = doors; } void honk() { [Link](brand
+ " honks!"); } } class ElectricCar extends Car { // IS-A Car, IS-A Vehicle (multilevel) int
battery; ElectricCar(String brand, int speed, int doors, int battery) { super(brand, speed,
doors); [Link] = battery; } void charge() { [Link](brand + " charging..."); }
} ElectricCar ec = new ElectricCar("Tesla", 250, 4, 100); [Link](); // inherited from Vehicle
[Link](); // inherited from Car [Link](); // own method

17. super Keyword — this vs super


Feature this super

Refers to Current object Parent class

Variable access [Link] — resolve shadowing [Link] — access hidden parent variable

Method call [Link]() [Link]() — call overridden parent version

Constructor call this(...) — same class constructor super(...) — parent class constructor

Restriction Must be first line in constructor Must be first line in constructor

class Animal { String name = "Animal"; void sound() { [Link]("Some sound"); } }


class Dog extends Animal { String name = "Dog"; // hides parent's 'name' void show() {
[Link](name); // "Dog" — child's variable [Link]([Link]); //
"Animal" — parent's variable } @Override void sound() { [Link](); // calls Animal's sound
first [Link]("Woof!"); } }

18. Non-Primitive (Reference) Types


Non-primitive types store a reference (memory address) pointing to the object in heap memory, not the value
itself. Default value is null.

Core Java Notes | Study Guide Page 10


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Non-Primitive Type Description

String Sequence of characters. Immutable. Stored in String Pool in heap.

Arrays Fixed-size container for same-type elements. int[], String[]...

Classes User-defined types: Student, Car, BankAccount...

Interfaces Reference types that define a contract.

Enums A fixed set of named constants: enum Day { MON, TUE, WED }

Wrapper Object versions of primitives: Integer, Double, Boolean...

19. Type Casting — Upcasting & Downcasting


Type Explanation

Upcasting (Implicit/Safe) Child class reference → Parent class reference. Automatic. Object is still a child —
you just see it through the parent lens. Can only access parent members via this
reference.

Downcasting (Explicit/Risky) Parent reference → Child class reference. Must be explicit. Can fail with
ClassCastException if the actual object is NOT of that type. Always check with
instanceof before downcasting.

class Animal { void eat() { [Link]("eating"); } } class Dog extends Animal { void
bark() { [Link]("Woof!"); } } // UPCASTING — automatic Animal a = new Dog(); // Dog
object, Animal reference [Link](); // works — eat() is in Animal // [Link](); // ERROR — Animal
reference can't see bark() // DOWNCASTING — manual if (a instanceof Dog) { // always check
first! Dog d = (Dog) a; // explicit downcast [Link](); // Woof! }

20. Polymorphism
Type Key Points

Compile-time (Method Overloading) Same method name, different parameters in the SAME class. Resolved by
compiler at compile time (static binding).

Runtime (Method Overriding) Child class redefines parent's method. Same name + same parameters. Resolved
by JVM at runtime (dynamic binding). Use @Override.

// OVERLOADING — same class, different parameters class Calc { 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; } } // OVERRIDING — child replaces parent's method class Shape { void draw() {
[Link]("Shape"); } } class Circle extends Shape { @Override void draw() {
[Link]("Circle"); } } class Triangle extends Shape { @Override void draw() {
[Link]("Triangle"); } } // Runtime polymorphism Shape[] shapes = { new Circle(),
new Triangle(), new Shape() }; for (Shape s : shapes) [Link](); // Circle | Triangle | Shape

21. Variable Hiding


Variable hiding happens in inheritance when a child class declares a variable with the SAME NAME as a
parent variable. Unlike method overriding (which is runtime/dynamic), variable hiding is compile-time/static —

Core Java Notes | Study Guide Page 11


Core Java Notes — Complete Syllabus Beginner to Interview Ready

the reference TYPE determines which variable is accessed, NOT the object type.
class Parent { String type = "Parent"; } class Child extends Parent { String type = "Child"; }
// hides parent's 'type' Parent p = new Child(); // upcasting [Link]([Link]); //
"Parent" — reference is Parent, so Parent's variable Child c = new Child();
[Link]([Link]); // "Child" — reference is Child, so Child's variable // CONTRAST
with method overriding (runtime): // Even if reference is Parent, overridden methods use the
CHILD's version

Interview tip: With methods → runtime decides (object type). With variables → compile time decides
(reference type). Variable hiding is generally considered bad practice — avoid it.

Core Java Notes | Study Guide Page 12


Core Java Notes — Complete Syllabus Beginner to Interview Ready

22. Method Overloading vs Method Overriding


Feature Method Overloading Method Overriding

Also called Compile-time / Static polymorphism Runtime / Dynamic polymorphism

Location Same class Parent and child class

Parameters Must be DIFFERENT Must be exactly SAME

Return type Can differ Must be same (or covariant)

Access modifier No restriction Child CANNOT make it more private

@Override Not used Always recommended

static methods Can be overloaded CANNOT be overridden (only hidden)

23. Encapsulation
Encapsulation = wrapping data + methods in one unit AND hiding the internal data from the outside. Achieved
by: (1) declaring fields private, (2) providing public getter/setter methods with optional validation.
public class Student { private String name; // hidden private int age; private double marks; //
Getter — read-only access public String getName() { return name; } public int getAge() { return
age; } public double getMarks() { return marks; } // Setter WITH validation — data protection
public void setName(String n) { if (n != null && ![Link]()) [Link] = n; else
[Link]("Invalid name!"); } public void setAge(int a) { if (a > 0 && a < 150)
[Link] = a; else [Link]("Invalid age!"); } public void setMarks(double m) { if (m
>= 0 && m <= 100) [Link] = m; else [Link]("Marks must be 0-100!"); } }

24. Abstraction
Abstraction means hiding complex implementation details and showing only what is necessary. You define
WHAT something does, not HOW. Achieved in Java using abstract classes and interfaces.

Feature Abstract Class Interface

Keyword abstract class interface

Abstract methods Yes (can also have concrete methods) All abstract by default (pre-Java 8)

Concrete methods Yes Only default/static (Java 8+)

Variables Any type public static final (constants) only

Constructor Yes No

Multiple inherit No — one extends only Yes — implements multiple

Best used when Related classes share common code Unrelated classes need same capability

25. Abstract Class

Core Java Notes | Study Guide Page 13


Core Java Notes — Complete Syllabus Beginner to Interview Ready

An abstract class cannot be instantiated (no objects directly). It may have abstract methods (no body) that child
classes MUST implement, plus concrete methods with full implementations.
abstract class Shape { String color; Shape(String color) { [Link] = color; } abstract double
area(); // child MUST implement abstract double perimeter(); // child MUST implement void
describe() { // shared concrete method [Link]("Color: "+color+" | Area: "+area());
} } class Circle extends Shape { double radius; Circle(String color, double r) { super(color);
[Link] = r; } @Override double area() { return 3.14 * radius * radius; } @Override double
perimeter() { return 2 * 3.14 * radius; } } class Rect extends Shape { double w, h; Rect(String
color, double w, double h) { super(color); this.w=w; this.h=h; } @Override double area() {
return w * h; } @Override double perimeter() { return 2 * (w + h); } } // Shape s = new Shape();
// ERROR — cannot instantiate abstract class Circle c = new Circle("red", 5); [Link](); //
Color: red | Area: 78.5

26. Interface
An interface defines a contract — a list of methods that implementing classes MUST provide. From Java 8,
interfaces can also have default and static methods. A class can implement multiple interfaces.
interface Flyable { void fly(); // abstract — MUST implement default void land() { // optional
to override (Java 8+) [Link]("Landing..."); } static void rules() { // called on
interface directly (Java 8+) [Link]("Aviation rules apply"); } } interface
Swimmable { void swim(); } // Implementing MULTIPLE interfaces class Duck implements Flyable,
Swimmable { @Override public void fly() { [Link]("Duck flying"); } @Override public
void swim() { [Link]("Duck swimming"); } // land() uses default — not required to
override } Duck d = new Duck(); [Link](); [Link](); [Link](); // Duck flying | Duck swimming |
Landing... [Link](); // Aviation rules apply // Polymorphism with interface Flyable f =
new Duck(); // upcasting [Link](); // Duck flying (runtime decides)

27. Has-A Relationship (Composition & Aggregation)


Relationship How Life Dependency Example

IS-A extends keyword Child cannot exist without parent Dog IS-A Animal
type

Has-A Field of another class Strong — inner object's lifecycle Car HAS-A Engine
(Composition) tied to outer

Has-A (Aggregation) Field reference Weak — inner object can exist Dept HAS-A Employee
independently

// COMPOSITION — Engine lives inside Car class Engine { int hp; Engine(int hp){[Link]=hp;} void
start(){[Link]("Engine ON");} } class Car { String brand; Engine engine; Car(String
brand, int hp) { [Link]=brand; [Link]=new Engine(hp); } void drive() { [Link]();
[Link](brand+" moving at "+[Link]+"hp"); } } // AGGREGATION — Employee exists
independently class Employee { String name; Employee(String n){name=n;} } class Dept { String
name; Employee manager; Dept(String n, Employee e){ name=n; manager=e; } } Employee e = new
Employee("Alice"); // created independently Dept d = new Dept("Engineering", e); // just a
reference

28. Packages
A package is a namespace (folder) that groups related classes. Prevents naming conflicts and provides access
control. Use import to bring classes from other packages.

Core Java Notes | Study Guide Page 14


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Package Key Classes Inside

[Link] String, Math, Object, System, Integer, Thread — auto-imported, no import needed

[Link] ArrayList, HashMap, Scanner, Arrays, Collections, Date, Optional

[Link] File, FileReader, FileWriter, BufferedReader, BufferedWriter, PrintWriter

[Link] Socket, ServerSocket, URL, HttpURLConnection

[Link] Connection, Statement, ResultSet, DriverManager

[Link] LocalDate, LocalTime, LocalDateTime, Period, Duration, DateTimeFormatter

29. Access Modifiers


Access modifiers control the visibility of classes, methods, and variables.

Modifier Same Class Same Package Subclass (any pkg) Any Class anywhere

private YES NO NO NO

default (no word) YES YES NO NO

protected YES YES YES NO

public YES YES YES YES

Best practice: Apply the Principle of Least Privilege. Make everything private first, then expose only what is
truly needed via public methods.

30. The 'final' Keyword


Applied To Effect

final variable Value cannot be changed after the first assignment. Becomes a constant.

final method Method cannot be overridden in any subclass.

final class Class cannot be extended (subclassed). E.g., String, Integer are final.

blank final Declared final but assigned exactly once — inside the constructor only.

final double PI = 3.14159; // PI = 3.0; // ERROR — cannot reassign final variable class Parent {
final void show() { [Link]("Parent"); } } class Child extends Parent { // void
show() { } // ERROR — cannot override final method } final class Utility { static int square(int
n){ return n*n; } } // class BetterUtil extends Utility { } // ERROR — cannot extend final class

31. Singleton Class


Singleton ensures only ONE instance of a class exists in the entire program and provides a global access point
to it. Common uses: Database connections, Logger, Configuration.
public class Config { private static Config instance = null; // holds the single instance
private Config() { // private — no one can call new Config() [Link]("Config

Core Java Notes | Study Guide Page 15


Core Java Notes — Complete Syllabus Beginner to Interview Ready

initialised"); } public static Config getInstance() { // global access point if (instance ==


null) { instance = new Config(); // created only ONCE } return instance; } public String
getAppName() { return "MyApp"; } } Config c1 = [Link](); Config c2 =
[Link](); [Link](c1 == c2); // true — exact same object!
[Link]([Link]()); // MyApp

32. Immutable Class


An immutable class cannot have its state changed after creation. String is the most famous example. Rules to
make one:
• Declare the class final (prevent subclassing)
• All fields private and final
• Initialise fields ONLY in the constructor
• Provide only getters — no setters
• Return a defensive copy of any mutable fields from getters
public final class ImmutablePoint { private final double x; private final double y; public
ImmutablePoint(double x, double y) { this.x=x; this.y=y; } public double getX() { return x; }
public double getY() { return y; } // No setters! Instead, return a NEW object public
ImmutablePoint translate(double dx, double dy) { return new ImmutablePoint(x+dx, y+dy); }
@Override public String toString() { return "("+x+", "+y+")"; } } ImmutablePoint p1 = new
ImmutablePoint(3.0, 4.0); ImmutablePoint p2 = [Link](1.0, 2.0); [Link](p1);
// (3.0, 4.0) — unchanged [Link](p2); // (4.0, 6.0) — new object

33. The Object Class


Every Java class implicitly extends [Link]. This is the root of the entire Java class hierarchy. Every
object you create automatically has these methods:

Method Purpose & Notes

toString() Returns a String representation. Default is ClassName@hashCode. Override for readable


output.

equals(Object o) Checks logical equality. Default checks reference (==). Override to compare content.

hashCode() Returns an int hash code. Must override together with equals() — HashMap depends on this.

getClass() Returns the runtime class of the object. Used in reflection.

clone() Creates a shallow copy. Class must implement Cloneable interface.

wait()/notify() Thread communication. Used inside synchronized blocks.

public class Person { String name; int age; Person(String n, int a) { name=n; age=a; } @Override
public String toString() { return "Person{name='"+name+"', age="+age+"}"; } @Override public
boolean equals(Object o) { if (this==o) return true; if (!(o instanceof Person)) return false;
Person p = (Person)o; return age==[Link] && [Link]([Link]); } @Override public int
hashCode() { return [Link]()*31 + age; } } Person p1 = new Person("Alice", 25); Person p2
= new Person("Alice", 25); [Link](p1); // Person{name='Alice', age=25}
[Link]([Link](p2)); // true — same content [Link](p1==p2); // false
— different objects

34. Wrapper Classes

Core Java Notes | Study Guide Page 16


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Wrapper classes are object versions of the 8 primitives. Needed because Collections can only hold objects, not
primitives.

Primitive Wrapper Key Methods

byte Byte [Link](str), Byte.MAX_VALUE (127)

short Short [Link](str), Short.MIN_VALUE

int Integer [Link](str), MAX_VALUE, toBinaryString(), toHexString()

long Long [Link](str), Long.MAX_VALUE

float Float [Link](str), isNaN(), isInfinite()

double Double [Link](str), Double.MAX_VALUE

char Character isDigit(c), isLetter(c), isUpperCase(c), toUpperCase(c)

boolean Boolean [Link](str), TRUE, FALSE constants

// Autoboxing — primitive → Wrapper (automatic) int prim = 42; Integer wrap = prim; //
auto-boxed ArrayList<Integer> list = new ArrayList<>(); [Link](10); // 10 auto-boxed to
Integer(10) // Unboxing — Wrapper → primitive (automatic) Integer w = [Link](99); int
p = w; // auto-unboxed // String conversions int num = [Link]("123"); // String → int
String s = [Link](456); // int → String String s2 = [Link](789); // int →
String [Link](Integer.MAX_VALUE); // 2147483647
[Link]([Link](10)); // 1010
[Link]([Link]('a')); // A
[Link]([Link]('5')); // true

Core Java Notes | Study Guide Page 17


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part C — Java 8+ Features

35. Lambda Expressions


A lambda expression is a short, anonymous function — no name, no class, no access modifier. Introduced in
Java 8. Used wherever a functional interface (interface with exactly ONE abstract method) is expected.
Syntax: (parameters) -> expression OR (parameters) -> { statements; }
// Before Java 8 — anonymous class (verbose) Runnable r1 = new Runnable() { @Override public
void run() { [Link]("Running"); } }; // Java 8 — lambda (concise) Runnable r2 = ()
-> [Link]("Running"); // Lambda with parameter [Link](name ->
[Link](name)); // Lambda with two parameters Comparator<Integer> comp = (a, b) -> a
- b; // Lambda with multiple statements Runnable r3 = () -> { [Link]("Step 1");
[Link]("Step 2"); }; // Common Functional Interfaces ([Link])
Predicate<Integer> isEven = n -> n % 2 == 0; [Link]([Link](4)); // true
Function<String, Integer> len = str -> [Link](); [Link]([Link]("Hello")); //
5 Consumer<String> print = s -> [Link](s); [Link]("Lambda!");
Supplier<String> greet = () -> "Good Morning!"; [Link]([Link]()); // Sorting
with lambda List<String> names = [Link]("Charlie", "Alice", "Bob"); [Link]((a, b) ->
[Link](b)); [Link]([Link]::println); // Method reference — even shorter

36. Stream API


Streams allow processing collections in a declarative, pipeline style. Streams are lazy and do NOT modify the
original collection. Pipeline = Source → Intermediate operations → Terminal operation
import [Link].*; import [Link].*; List<Integer> nums = [Link](5, 3, 8, 1,
9, 2, 7, 4, 6, 10); // filter() — keep matching elements List<Integer> evens = [Link]()
.filter(n -> n % 2 == 0) .collect([Link]()); // [8, 2, 4, 6, 10] // map() — transform
each element List<Integer> doubled = [Link]() .map(n -> n * 2)
.collect([Link]()); // sorted() + limit() List<Integer> top3 = [Link]()
.sorted() .limit(3) .collect([Link]()); // [1, 2, 3] // reduce() — combine to single
value int sum = [Link]().reduce(0, Integer::sum); // 55 // count / min / max long count =
[Link]().filter(n -> n > 5).count(); // 5 Optional<Integer> max =
[Link]().max(Integer::compareTo); [Link]([Link]()); // 10 // anyMatch /
allMatch / noneMatch boolean hasNeg = [Link]().anyMatch(n -> n < 0); // false boolean
allPos = [Link]().allMatch(n -> n > 0); // true // Chaining multiple operations
List<String> names = [Link]("Charlie", "Alice", "Bob", "Dave"); List<String> result =
[Link]() .filter(n -> [Link]() > 3) .map(String::toUpperCase) .sorted()
.collect([Link]()); // [CHARLIE, DAVE]

37. Time & Date API ([Link] — Java 8+)


Java 8 replaced the old Date/Calendar with the [Link] package. The new API is immutable, clear, and
thread-safe.
import [Link].*; import [Link]; // LocalDate — date only, no
time LocalDate today = [Link](); // 2026-04-04 LocalDate birthday = [Link](2000,
6, 15); [Link]([Link]()); // SATURDAY
[Link]([Link](10)); // 10 days later
[Link]([Link](birthday)); // false // LocalTime — time only, no date
LocalTime now = [Link](); // 14:30:45 LocalTime meeting = [Link](9, 30);
[Link]([Link](2)); // 11:30 // LocalDateTime — both date and time
LocalDateTime dt = [Link](); // Period — difference in years/months/days Period age

Core Java Notes | Study Guide Page 18


Core Java Notes — Complete Syllabus Beginner to Interview Ready

= [Link](birthday, today); [Link]("Age: " + [Link]() + " years"); //


Duration — difference in hours/minutes/seconds Duration d = [Link](meeting,
[Link]()); [Link]("Hours since meeting: " + [Link]()); // Formatting and
Parsing DateTimeFormatter fmt = [Link]("dd/MM/yyyy"); String formatted =
[Link](fmt); // "04/04/2026" LocalDate parsed = [Link]("15/06/2000", fmt);

Core Java Notes | Study Guide Page 19


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part D — Exception Handling

38. Exception Handling — try / catch / finally / throw / throws


An exception is an event that disrupts normal program flow. Java provides a structured mechanism to handle
exceptions gracefully — so the program continues or exits cleanly instead of crashing with an ugly error.

Exception Category Description & Examples

Checked Exception Checked at COMPILE time. You must handle with try-catch OR declare with
throws. Examples: IOException, SQLException, ClassNotFoundException,
FileNotFoundException

Unchecked (Runtime) Exception Checked at RUNTIME only. Usually programming bugs. Not required to declare.
Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException, ArithmeticException

Error Serious JVM-level problems. You generally should NOT catch these. Examples:
StackOverflowError, OutOfMemoryError

// ■■ try-catch-finally ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ try { int[] arr


= new int[5]; arr[10] = 100; // throws ArrayIndexOutOfBoundsException } catch
(ArrayIndexOutOfBoundsException e) { [Link]("Array error: " + [Link]()); }
catch (Exception e) { // catches any other exception [Link]("General: " +
[Link]()); } finally { [Link]("Always runs — great for cleanup (close files,
DB connections)"); } // ■■ Multi-catch (Java 7+)
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ try { String s = null; [Link](); } catch
(NullPointerException | IllegalArgumentException e) { [Link]("Caught: " +
[Link]().getSimpleName()); } // ■■ throw — manually raise an exception
■■■■■■■■■■■■■■■■■■■■■■■ void validateAge(int age) { if (age < 0 || age > 150) throw new
IllegalArgumentException("Age must be 0-150, got: " + age); } // ■■ throws — declare checked
exceptions ■■■■■■■■■■■■■■■■■■■■■■■ void readFile(String path) throws IOException {
FileReader fr = new FileReader(path); // might throw IOException } // ■■ Custom Exception
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ class InsufficientFundsException extends
Exception { double amount; InsufficientFundsException(double a) { super("Insufficient funds!
Needed: " + a); [Link] = a; } } class Account { double balance = 1000; void withdraw(double
amount) throws InsufficientFundsException { if (amount > balance) throw new
InsufficientFundsException(amount); balance -= amount; } } Account acc = new Account(); try {
[Link](500); // OK [Link](800); // throws — only 500 left } catch
(InsufficientFundsException e) { [Link]([Link]()); } // ■■ try-with-resources
— auto-closes resources (Java 7+) ■■■■■■ try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) { String line = [Link](); [Link](line); } // br is
automatically closed here, even if exception occurs

Core Java Notes | Study Guide Page 20


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part E — File Handling

39. File Handling ([Link] & [Link])


File handling lets you read from and write to files on disk. Java provides two main approaches: the classic
[Link] package and the modern [Link] package (recommended).

Class Package Purpose

File [Link] Represents a file/directory path. Create, delete, check existence, list contents.

FileWriter [Link] Write text to a file character by character. Slow without buffering.

FileReader [Link] Read text from a file character by character.

BufferedWriter [Link] Wraps FileWriter for faster writing. Adds newLine() method.

BufferedReader [Link] Wraps FileReader for faster reading. readLine() returns one line at a time.

PrintWriter [Link] Convenient: has print(), println(), printf() for writing.

Files (NIO) [Link] Modern API. readAllLines(), write(), copy(), delete(), exists().

Path [Link] Represents a file/directory path in NIO. Use [Link]('[Link]').

import [Link].*; import [Link].*; import [Link]; // ■■ Writing to a file


■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ try (BufferedWriter bw = new
BufferedWriter(new FileWriter("[Link]"))) { [Link]("Line 1: Hello Java"); [Link]();
[Link]("Line 2: File Handling"); } catch (IOException e) { [Link]("Write error: "
+ [Link]()); } // Append to existing file (true = append mode) try (FileWriter fw = new
FileWriter("[Link]", true); BufferedWriter bw = new BufferedWriter(fw)) { [Link]("Line 3:
Appended"); [Link](); } catch (IOException e) { [Link](); } // ■■ Reading from a
file ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ try (BufferedReader br = new
BufferedReader(new FileReader("[Link]"))) { String line; while ((line = [Link]()) !=
null) { [Link](line); } } catch (FileNotFoundException e) {
[Link]("File not found!"); } catch (IOException e) { [Link](); } // ■■
Modern [Link] ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Path path =
[Link]("[Link]"); List<String> lines = [Link](path); // read all at once
[Link]([Link]::println); List<String> content = [Link]("First", "Second", "Third");
[Link](path, content); // write all at once // ■■ File operations
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ File file = new File("[Link]");
[Link]([Link]()); // true / false [Link]([Link]()); // size
in bytes [Link]([Link]()); // "[Link]"
[Link]([Link]()); // full path [Link](); // delete file new
File("myFolder").mkdirs(); // create folder (+ any missing parents)

Core Java Notes | Study Guide Page 21


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part F — Multithreading

40. Multithreading
A thread is the smallest unit of execution. Multithreading lets a Java program run multiple tasks concurrently —
e.g., one thread downloads a file while another updates the UI. Java provides built-in threading support.

Thread State What It Means

New Thread object created with new Thread(). start() not yet called.

Runnable start() called. Thread is ready, waiting for CPU to schedule it.

Running Thread is actively executing its run() method code.

Blocked/Waiting Thread is paused — waiting for a lock, I/O, sleep(), or join().

Terminated run() has completed. Thread cannot be restarted.

// ■■ Method 1: Extend Thread ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ class MyThread extends


Thread { String task; MyThread(String t) { [Link] = t; } @Override public void run() { for
(int i=1; i<=3; i++) [Link](task + " - step " + i); } } // ■■ Method 2: Implement
Runnable (recommended) ■■■■■■■■■■■■■■ class MyTask implements Runnable { @Override public
void run() { [Link]("Task in: " + [Link]().getName()); } } // ■■
Method 3: Lambda (Java 8+) ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ Thread t3 = new Thread(() ->
[Link]("Lambda thread")); // Starting threads MyThread t1 = new
MyThread("Download"); MyThread t2 = new MyThread("Upload"); [Link](); [Link](); // run
concurrently [Link](); // main thread WAITS for t1 to finish [Link](1000); // pause
current thread for 1 second // ■■ Synchronisation — prevent race conditions ■■■■■■■■■■■■■■■
class Counter { private int count = 0; public synchronized void increment() { count++; } // one
thread at a time public synchronized int getCount() { return count; } } // ■■ Thread Pool —
much better than raw threads ■■■■■■■■■■■■■■ import [Link].*; ExecutorService
pool = [Link](4); // 4 worker threads for (int i=0; i<10; i++) { int id =
i; [Link](() -> [Link]("Task "+id+" by "+[Link]().getName())); }
[Link](); // no more new tasks [Link](10, [Link]); // ■■
volatile — visible to all threads immediately ■■■■■■■■■■■ volatile boolean running = true; //
no thread caches stale value

Core Java Notes | Study Guide Page 22


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part G — Collections Framework

41. Collections Framework


The Collections Framework provides ready-made, optimised data structures. Unlike arrays (fixed size),
collections grow and shrink dynamically. All collections are in [Link] and can only store objects (use wrapper
classes for primitives).

Interface Main Implementations Key Characteristics

List ArrayList, LinkedList, Vector Ordered. Allows duplicates. Index-based access.

Set HashSet, LinkedHashSet, TreeSet No duplicates. HashSet unordered, TreeSet sorted.

Queue LinkedList, PriorityQueue, ArrayDeque FIFO order. PriorityQueue sorts by priority.

Deque ArrayDeque, LinkedList Double-ended queue. addFirst/addLast,


removeFirst/removeLast.

Map HashMap, LinkedHashMap, TreeMap Key-value pairs. Keys unique. Not a Collection technically.

ArrayList
Dynamic array. Fast index access O(1). Slow insert/delete in middle O(n). Default choice for lists.
ArrayList<String> fruits = new ArrayList<>(); [Link]("Apple"); [Link]("Banana");
[Link]("Cherry"); [Link](1, "Mango"); // insert at index 1 [Link](0, "Avocado"); //
replace at index 0 [Link]([Link](2)); // Cherry
[Link]([Link]()); // 4 [Link]([Link]("Banana")); // true
[Link]("Banana"); // remove by value [Link](0); // remove by index
[Link](fruits); // sort alphabetically [Link](fruits); // reverse order

LinkedList
Doubly-linked list. Fast O(1) add/remove at ends. Slow O(n) index access. Also implements Deque.
LinkedList<Integer> ll = new LinkedList<>(); [Link](10); [Link](20); [Link](30);
[Link](5); // [5, 10, 20, 30] [Link](40); // [5, 10, 20, 30, 40] [Link](); //
removes 5 [Link](); // removes 40 [Link]([Link]()); // 10 — view head
without removing [Link]([Link]()); // 10 — remove and return head

HashMap
Key-value pairs. Keys are unique. Order NOT guaranteed. get/put O(1) average.
HashMap<String, Integer> scores = new HashMap<>(); [Link]("Alice", 95); [Link]("Bob",
82); [Link]("Carol", 88); [Link]("Alice", 99); // overwrites Alice's score
[Link]([Link]("Bob")); // 82 [Link]([Link]("Dave",0));
// 0 (key missing) [Link]([Link]("Carol")); // true
[Link]("Carol"); for ([Link]<String,Integer> e : [Link]())
[Link]([Link]() + " -> " + [Link]());

HashSet, TreeMap, PriorityQueue

Core Java Notes | Study Guide Page 23


Core Java Notes — Complete Syllabus Beginner to Interview Ready

// HashSet — no duplicates, unordered HashSet<String> set = new HashSet<>(); [Link]("Java");


[Link]("Python"); [Link]("Java"); // duplicate ignored [Link]([Link]()); // 2
// Set operations HashSet<Integer> a = new HashSet<>([Link](1,2,3,4)); HashSet<Integer>
b = new HashSet<>([Link](3,4,5,6)); Set<Integer> union = new HashSet<>(a);
[Link](b); // 1-6 Set<Integer> intersect = new HashSet<>(a); [Link](b);//
3,4 Set<Integer> diff = new HashSet<>(a); [Link](b); // 1,2 // TreeMap — sorted by key
TreeMap<String, Integer> tm = new TreeMap<>(); [Link]("Banana",2); [Link]("Apple",5);
[Link]("Cherry",1); [Link](tm); // {Apple=5, Banana=2, Cherry=1}
[Link]([Link]()); // Apple [Link]([Link]()); // Cherry //
PriorityQueue — min-heap PriorityQueue<Integer> pq = new PriorityQueue<>(); [Link](30);
[Link](10); [Link](50); [Link](20); [Link]([Link]()); // 10 (smallest always at
top) [Link]([Link]()); // 10 (removes smallest)

Collections Comparison Summary


Collection Order Duplicates Null OK Thread-Saf Best For
e

ArrayList Insertion Yes Yes No Random access, general list

LinkedList Insertion Yes Yes No Frequent add/remove at ends

HashMap None Keys: No 1 null key No Fast key-based lookup

LinkedHashMa Insertion Keys: No 1 null key No Ordered key-value pairs


p

TreeMap Sorted Keys: No No No Sorted key-value pairs

HashSet None No Yes No Unique elements, fast contains()

TreeSet Sorted No No No Sorted unique elements

PriorityQueue Priority Yes No No Min/Max heap operations

Hashtable None Keys: No No Yes Legacy thread-safe map (use


ConcurrentHashMap instead)

Core Java Notes | Study Guide Page 24


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Part H — Top Java Interview Questions & Answers


These are the most commonly asked Core Java interview questions for freshers and junior developers. Each
answer is written in clear, simple language.

Q: 1. What is Java? Why is it platform-independent?

A: Java is a high-level, object-oriented, strongly typed programming language. It is platform-independent


because Java source code is compiled into bytecode (.class files) by the javac compiler. This bytecode can
run on ANY machine that has a JVM installed — without needing to recompile. This is the 'Write Once, Run
Anywhere' principle. The JVM acts as a universal interpreter for bytecode.

Q: 2. Explain the difference between JDK, JRE, and JVM.

A: JVM (Java Virtual Machine) executes bytecode. It is platform-specific — there are separate JVMs for
Windows, Linux, Mac. JRE (Java Runtime Environment) = JVM + core class libraries. Needed to RUN Java
programs. JDK (Java Development Kit) = JRE + development tools (javac compiler, debugger, javadoc).
Needed to WRITE and COMPILE Java programs. Relationship: JDK contains JRE, which contains JVM.

Q: 3. What is the difference between == and .equals()?

A: == compares references — it checks if both variables point to the exact same object in memory. .equals()
compares content (logical equality). For primitive types, == compares values. For objects (especially Strings),
always use .equals() for content comparison. Example: String a = new String('Hi'); String b = new String('Hi');
a==b is false (different objects), but [Link](b) is true (same content). Exception: String literals like 'Hi'=='Hi'
may be true due to the String Pool.

Q: 4. What are the 4 pillars of OOP? Explain with a real example.

A: Using a BankAccount example: (1) Encapsulation — balance is private; only accessible via deposit() and
withdraw() methods that validate inputs. Data is protected. (2) Inheritance — SavingsAccount extends
BankAccount, inheriting all account operations and adding interest calculation. (3) Polymorphism —
calculateInterest() behaves differently in SavingsAccount vs CurrentAccount (method overriding). (4)
Abstraction — the user calls withdraw() without knowing if the bank uses SQL, NoSQL, or a blockchain ledger.
Complexity is hidden.

Q: 5. What is method overloading vs method overriding?

A: Overloading: same method name in the SAME class, different parameters (type/number/order). Resolved
at compile time — static/compile-time polymorphism. Return type alone cannot differentiate overloaded
methods. Overriding: child class provides a new implementation for a method already defined in the parent.
Same name + same parameters. Resolved at runtime — dynamic polymorphism. Use @Override. Cannot
make the method more private in the child. Static and final methods cannot be overridden.

Core Java Notes | Study Guide Page 25


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Q: 6. What is the difference between abstract class and interface?

A: Abstract class: can have abstract AND concrete methods, constructors, any access modifiers, instance
variables. A class can extend only ONE abstract class. Interface (Java 8+): can have abstract methods,
default methods (with body), and static methods. All variables are public static final (constants). No
constructors. A class can implement MULTIPLE interfaces. Use abstract class when related classes share
code (IS-A). Use interface for capabilities needed by unrelated classes (CAN-DO) or when multiple inheritance
is needed.

Q: 7. What is the 'static' keyword? Can static methods access instance variables?

A: static means the member belongs to the CLASS itself, not to any specific object. A static variable is shared
by ALL objects — one copy. A static method can be called without creating an object: [Link](). A
static block runs once when the class is loaded. NO — a static method CANNOT directly access instance
(non-static) variables, because instance members need an object to exist and static methods can be called
without any object. However, a static method CAN access static variables.

Q: 8. What is the difference between String, StringBuilder, and StringBuffer?

A: String is IMMUTABLE — every modification (concat, replace) creates a NEW String object. Slow for many
modifications. StringBuilder is MUTABLE — modifies the same object without creating new ones. Fast, but
NOT thread-safe. Use in single-threaded code. StringBuffer is MUTABLE and thread-safe (all methods are
synchronized). Slower than StringBuilder due to synchronisation overhead. Use in multi-threaded code. Rule:
fixed text → String. Many changes in one thread → StringBuilder. Many changes across threads →
StringBuffer.

Q: 9. What is the difference between ArrayList and LinkedList?

A: ArrayList uses a dynamic array. get(i) is O(1) — very fast random access. add/remove in the middle is O(n)
— must shift elements. Best for frequent reads. LinkedList uses a doubly linked list. get(i) is O(n) — must
traverse. addFirst/addLast/removeFirst/removeLast are O(1) — very fast. Best for frequent
insertions/deletions at ends. Memory: LinkedList uses more memory per element (data + 2 pointers). For most
use cases ArrayList is preferred because modern iteration is still fast.

Q: 10. What is the difference between HashMap and TreeMap?

A: HashMap: no guaranteed order, uses hashing internally, get/put O(1) average, allows one null key and
multiple null values. TreeMap: keys are SORTED in natural or custom order, uses Red-Black tree, get/put
O(log n), does NOT allow null keys. Choose HashMap when you need fast unsorted lookup. Choose TreeMap
when you need entries in sorted key order (e.g., alphabetical menu, range queries). Both are NOT thread-safe
— use ConcurrentHashMap for thread safety.

Core Java Notes | Study Guide Page 26


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Q: 11. What is the difference between throw and throws?

A: 'throw' is used INSIDE a method body to ACTUALLY RAISE an exception at a specific line: throw new
IllegalArgumentException('Invalid age'). Only one exception at a time. 'throws' is used in the METHOD
SIGNATURE to DECLARE that the method MIGHT throw one or more checked exceptions, warning callers to
handle them: public void readFile() throws IOException, SQLException. It does not throw anything itself — it is
just a warning. Multiple exceptions can be declared with throws, separated by commas.

Q: 12. What is Garbage Collection? How does it work?

A: Garbage Collection (GC) is Java's automatic memory management. When an object in the heap is no
longer referenced by any variable (unreachable), the GC automatically reclaims its memory. Programmers do
NOT manually free memory (unlike C/C++). The GC runs as a background daemon thread. You can suggest it
runs with [Link]() but there is no guarantee of when it will run. Before collecting, GC calls finalize() on the
object (deprecated in Java 9+). Common algorithms: Mark-and-Sweep, Generational GC, G1 GC.

Q: 13. What is the 'final' keyword? How is it used?

A: Applied to a variable: value cannot be changed after assignment (constant). Applied to a method: cannot be
overridden in any subclass. Applied to a class: cannot be extended — String, Integer, and Math are all final
classes. Blank final variable: declared final but assigned exactly once in the constructor. static final creates
class-level constants: public static final double PI = 3.14159. The final keyword is important in immutable
classes and Singleton patterns.

Q: 14. What is Singleton? How do you implement it?

A: Singleton ensures only ONE instance of a class exists in the entire application and provides a global access
point. Steps: (1) Make the constructor private — no external new allowed. (2) Declare a private static variable
of the class type. (3) Provide a public static getInstance() method that creates the instance only the first time it
is called, then returns the same instance on all future calls. Common uses: DB connections, Logger, Config.
For thread safety, use synchronized getInstance() or double-checked locking pattern.

Q: 15. What is an Immutable class? Name examples and how to create one.

A: An immutable class cannot have its state changed after creation. Famous examples: String, Integer,
Double, LocalDate. To create: (1) Declare class as final. (2) Make all fields private and final. (3) Initialise all
fields in the constructor only. (4) Provide only getters — no setters. (5) For mutable fields, return a defensive
copy in the getter. Benefits: automatically thread-safe (no synchronisation needed), can be safely cached and
shared as HashMap keys, predictable state.

Core Java Notes | Study Guide Page 27


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Q: 16. What is the difference between Comparable and Comparator?

A: Comparable ([Link]): implemented BY the class itself. Has one method: compareTo(Object). Defines the
NATURAL ordering of the class. Example: String, Integer implement Comparable. Comparator ([Link]): a
SEPARATE class or lambda that defines CUSTOM ordering. Has one method: compare(T o1, T o2). Use it
when you need multiple sort orders, or cannot modify the class. Example: sort Employees by salary in one
place, by name in another. With Java 8, Comparator can be a concise lambda:
[Link](Employee::getSalary).

Q: 17. What is autoboxing and unboxing? Any pitfalls?

A: Autoboxing: Java automatically converts a primitive to its Wrapper object (int → Integer) when needed —
e.g., when adding to a Collection or assigning to a Wrapper variable. Unboxing: automatic conversion back
from Wrapper to primitive (Integer → int). Pitfalls: (1) Unboxing a null wrapper throws NullPointerException —
always check for null before unboxing. (2) Autoboxing in tight loops creates many temporary objects and can
hurt performance. (3) Integer uses a cache (-128 to 127), so [Link](100)==[Link](100) is
true, but [Link](200)==[Link](200) is false!

Q: 18. What are lambda expressions and functional interfaces?

A: A lambda expression (Java 8+) is a concise anonymous function — no name, no class, no access modifier.
Syntax: (parameters) -> expression. A functional interface has exactly ONE abstract method (SAM — Single
Abstract Method). @FunctionalInterface annotation enforces this. Common ones: Predicate (test — returns
boolean), Function (apply — T to R), Consumer (accept — takes T, returns void), Supplier (get — produces
T). Lambdas make code dramatically shorter for sorting, event handling, stream operations, and threading.

Q: 19. What is the Stream API? What are intermediate and terminal operations?

A: Stream API ([Link], Java 8+) processes collections in a declarative pipeline style. Streams are
LAZY — processing only starts at the terminal operation. Pipeline: Source → Intermediate operations →
Terminal operation. Intermediate operations (return another Stream, lazy): filter(), map(), sorted(), distinct(),
limit(), skip(), flatMap(). Terminal operations (trigger processing, return result): collect(), count(), reduce(),
forEach(), min(), max(), findFirst(), anyMatch(), allMatch(). A stream can be consumed only ONCE — a
second terminal operation throws IllegalStateException. Use parallelStream() for parallel processing.

Q: 20. What is the difference between checked and unchecked exceptions?

A: Checked exceptions are verified by the compiler at compile time. You MUST either surround with try-catch
or declare with 'throws' in the method signature. Examples: IOException, SQLException,
ClassNotFoundException, FileNotFoundException. Unchecked exceptions (subclasses of RuntimeException)
are NOT checked at compile time. They represent programming bugs — null access, invalid array index, etc.
You do NOT need to declare them. Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException, ArithmeticException. Errors (StackOverflowError, OutOfMemoryError) are also
unchecked and represent severe JVM problems.

Core Java Notes | Study Guide Page 28


Core Java Notes — Complete Syllabus Beginner to Interview Ready

Study Tips & Recommended Path


Congratulations! You have covered the complete Core Java syllabus — from Tokens all the way through to
the Collections Framework and Interview Q&A. Now the key is PRACTICE. Reading is not enough — write
code every single day.

Recommended Study Order (Week by Week):


• Week 1-2: Tokens, Keywords, Identifiers, Data Types, Casting
• Week 3-5: OOP — Classes, Objects, Constructors, Inheritance, Polymorphism
• Week 6-7: OOP Advanced — Abstraction, Interface, Encapsulation, final, static
• Week 8: Special Classes — Singleton, Immutable, Object class, Wrapper
• Week 9: Java 8 Features — Lambdas, Streams, Date-Time API
• Week 10: Exception Handling + File Handling
• Week 11: Multithreading — Thread, Runnable, synchronized, ExecutorService
• Week 12: Collections — ArrayList, LinkedList, HashMap, HashSet, TreeMap
• Ongoing: Revise all Interview Q&A; until you can answer without reading

Practice Projects (Build These!):


• Student Grade Management System — OOP + Collections
• Simple Bank Account App — Encapsulation + Exception Handling
• File-based To-Do List — File Handling + Collections
• Multi-threaded Download Simulator — Multithreading
• Library Book Management System — all concepts combined

Final advice: Don't just memorise answers — understand the WHY behind each concept. If an interviewer
asks a follow-up, you should explain it from first principles. Write code, make mistakes, debug, and learn. That
is how real Java developers are made!

Core Java Notes | Study Guide Page 29

You might also like