0% found this document useful (0 votes)
13 views34 pages

Core Java Notes

The document is a comprehensive guide to Core Java, aimed at transforming beginners into placement-ready Java experts. It covers foundational concepts, language fundamentals, object-oriented programming, core APIs, memory management, modern Java features, and placement preparation, structured across 28 chapters. The guide includes practical examples, interview tips, and mini projects to enhance learning and application of Java skills.
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)
13 views34 pages

Core Java Notes

The document is a comprehensive guide to Core Java, aimed at transforming beginners into placement-ready Java experts. It covers foundational concepts, language fundamentals, object-oriented programming, core APIs, memory management, modern Java features, and placement preparation, structured across 28 chapters. The guide includes practical examples, interview tips, and mini projects to enhance learning and application of Java skills.
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

PUBLIC CLASS CAREER { PUBLIC STATIC VOID MAIN() { LEARN("JAVA"); } }

From absolute beginner to placement-ready Java expert — for students, freshers &
aspiring software engineers.

Fundamentals → Advanced Interview Prep Company-wise Questions Mini Projects

v1.0 — 2026 Edition 28 Chapters · Practice Problems · Cheatsheet

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


Table of Contents
PART I — FOUNDATIONS
01. Introduction, History & Features of Java 02. JVM, JRE, JDK & Java Architecture
03. Installation, First Program & Program Structure 04. Input & Output in Java

PART II — LANGUAGE FUNDAMENTALS


05. Variables, Data Types & Type Casting 06. Operators
07. Control Statements & Loops 08. Arrays
09. Strings, StringBuilder & StringBuffer

PART III — OBJECT-ORIENTED PROGRAMMING


10. Classes, Objects & Constructors 11. Encapsulation, Inheritance & Polymorphism
12. Abstraction & Interfaces 13. Overloading, Overriding & Keywords
14. Packages & Access Modifiers

PART IV — CORE APIs & DATA STRUCTURES


15. Wrapper Classes & Exception Handling 16. Collections — List, Set & Queue
17. Collections — Map, Generics & Comparators

PART V — MEMORY & CONCURRENCY


18. Memory Management & Garbage Collection 19. Multithreading & Concurrency
20. File Handling & Serialization

PART VI — MODERN JAVA & ADVANCED TOPICS


21. Java 8 Features 22. Inner Classes, Enums, Annotations & Reflection
23. Design Principles, SOLID & Best Practices

PART VII — PLACEMENT PREPARATION


24. Interview Questions — Beginner & Intermediate 25. Interview Questions — Advanced & Scenario-Based
26. Company-Wise Interview Questions

PART VIII — PRACTICE & REVISION


27. Mini Projects & Real-World Use Cases 28. Cheatsheet, Roadmap & Placement Checklist

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART I — FOUNDATIONS · CHAPTER 01

Introduction, History & Features of Java


Java is a general-purpose, class-based, object-oriented programming language designed to have as few implementation
dependencies as possible — write once, run anywhere (WORA). It compiles to bytecode that runs on any device with a
Java Virtual Machine, making it a top choice for backend systems, Android apps, and enterprise software.

A Brief History
Java was created by James Gosling and team at Sun Microsystems, released publicly in 1995. Originally named "Oak" for
embedded consumer devices, it was rebuilt around portability for the emerging web. Sun was acquired by Oracle in 2010,
which continues to steward the language today. Java has moved to a faster, time-boxed release cycle since Java 9 — a
new version every six months (LTS versions like 8, 11, 17, 21 are the ones most companies standardize on).

Key Features of Java


Feature What it Means

Platform-independent Bytecode runs on any OS with a JVM

Object-oriented Everything modeled as classes & objects

Simple & familiar C/C++-like syntax, no pointers

Secure Runs in a sandboxed JVM, no direct memory access

Robust Strong type checking, exception handling, GC

Multithreaded Built-in support for concurrent execution

High performance JIT compiler translates bytecode to native code

Distributed Rich networking libraries (RMI, sockets)

Why Java Stays Popular for Placements


Backbone of enterprise backend systems — banking, insurance, e-commerce at scale.
Powers the Android SDK, so mobile roles screen for it too.
Massive ecosystem: Spring, Hibernate, Kafka, Android — all Java/JVM-based.
Almost every service-based company (TCS, Infosys, Wipro, Accenture, Cognizant) hires and trains on Core Java first.

INTERVIEW TIP
"Why Java?" is a near-guaranteed opener. Anchor your answer in WORA, the mature ecosystem, and strong OOP fundamentals
— not just "it was my college syllabus."

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART I — FOUNDATIONS · CHAPTER 02

JVM, JRE, JDK & Java Architecture


These three acronyms are the single most-asked "explain the basics" question in Core Java interviews — know exactly
what nests inside what.

JDK (Java Development Kit)

JRE (Java Runtime Environment)

JVM (Java Virtual Machine)

+ core class libraries

+ compiler (javac), debugger, tools

Term Purpose Who Needs It

JVM Executes bytecode, manages memory & GC Everyone running Java

JRE JVM + standard libraries needed to run apps End users

JDK JRE + compiler & dev tools Developers

How Java Code Executes


[Link] ⟶ javac (compiler) ⟶ [Link] (bytecode) ⟶

JVM: Classloader → Bytecode Verifier → JIT/Interpreter ⟶ Output

The JVM's Just-In-Time (JIT) compiler converts hot bytecode paths to native machine code at runtime, which is why Java
is much faster than a pure interpreter despite the "write once, run anywhere" abstraction.

INTERVIEW TIP
JVM is platform-dependent (a different build per OS) but bytecode is platform-independent — that distinction is what makes
WORA possible, and interviewers love probing it.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART I — FOUNDATIONS · CHAPTER 03

Installation, First Program & Program Structure


Installation & Setup
Download a JDK (Adoptium Temurin or Oracle JDK) — pick an LTS version like 17 or 21.
Set the JAVA_HOME environment variable and add its bin to PATH.
Verify with java -version and javac -version in a terminal.
Use an IDE — IntelliJ IDEA, Eclipse, or VS Code with the Java extension pack — for real project work.

Your First Program


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Placement!");
}
}

Compile with javac [Link] , then run with java HelloWorld . The class name must match the filename
exactly for a public class.

Anatomy of a Java Program


Part Meaning

public class HelloWorld Class declaration — every program is a class

public static void main(String[] args) Entry point the JVM calls first

[Link]() Prints to standard output with a newline

main must be exactly public static void main(String[] args) — public so the JVM can call it from outside, static so
it runs without creating an object, void because it returns nothing to the OS.

COMMON MISTAKE
Forgetting that only one public class is allowed per file, and it must share the file's name — a frequent freshman compile error.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART I — FOUNDATIONS · CHAPTER 04

Input & Output in Java


Reading Input with Scanner
import [Link];

public class InputDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link](name + " is " + age + " years old.");
[Link]();
}
}

Output Options
Method Behavior

[Link]() Prints without a trailing newline

[Link]() Prints with a trailing newline

[Link]() Formatted output, e.g. %d, %s, %.2f

BufferedReader Faster line-based input for large data / competitive coding

PRACTICE
Write a program that reads two integers with Scanner and prints their sum, difference, and product using printf.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART II — LANGUAGE FUNDAMENTALS · CHAPTER 05

Variables, Data Types & Type Casting


Primitive Data Types
Type Size Default Example

byte 8-bit 0 byte b = 10;

short 16-bit 0 short s = 100;

int 32-bit 0 int x = 42;

long 64-bit 0L long l = 100000L;

float 32-bit 0.0f float f = 3.14f;

double 64-bit 0.0d double d = 3.14159;

char 16-bit '\u0000' char c = 'A';

boolean 1-bit (JVM-defined) false boolean ok = true;

Primitive vs Non-Primitive
Primitives (int, char, boolean...) store actual values directly on the stack. Non-primitives — Strings, arrays, classes,
interfaces — are reference types: the variable holds a reference (pointer) to an object on the heap.

Type Casting
// Widening (implicit) — small to large, safe
int i = 100;
double d = i; // 100.0

// Narrowing (explicit) — large to small, may lose data


double price = 99.99;
int rounded = (int) price; // 99, decimal truncated

Order: byte → short → int → long → float → double . Widening happens automatically; narrowing always needs an
explicit cast.

INTERVIEW TIP
"Why is char 16-bit in Java?" — because Java uses Unicode (UTF-16) internally, not ASCII, so it can represent international
characters natively.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART II — LANGUAGE FUNDAMENTALS · CHAPTER 06

Operators
Category Operators Notes

Arithmetic +-*/% % is remainder, not just for integers

Relational == != > < >= <= Return boolean

Logical && || ! && and || short-circuit

Bitwise & | ^ ~ << >> >>> >>> is unsigned right shift

Assignment = += -= *= /= %= Compound forms implicitly cast

Ternary condition ? a : b Shorthand for simple if-else

int a = 5, b = 2;
[Link](a / b); // 2 (integer division)
[Link](a % b); // 1
[Link](a & b); // 0 (bitwise AND)
[Link](a << 1); // 10 (shift left = multiply by 2)

String result = (a > b) ? "a wins" : "b wins"; // ternary

INTERVIEW TIP
Know the difference between == on primitives (value comparison) vs objects (reference comparison) — it's the setup for almost
every String-equality trick question.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART II — LANGUAGE FUNDAMENTALS · CHAPTER 07

Control Statements & Loops


if / else if / else & switch
int marks = 72;
if (marks >= 90) [Link]("A grade");
else if (marks >= 60) [Link]("B grade");
else [Link]("Needs improvement");

switch (day) {
case 1 -> [Link]("Monday");
case 2 -> [Link]("Tuesday");
default -> [Link]("Other day");
}

Loops
Loop Use When

for Number of iterations is known upfront

while Condition checked before each iteration, count unknown

do-while Must run at least once (e.g. menus)

enhanced for (for-each) Iterating arrays/collections without an index

int[] nums = {2, 4, 6, 8};


for (int n : nums) {
[Link](n);
}

PRACTICE
Print the Fibonacci sequence up to n terms using a for loop, then rewrite it using a while loop.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART II — LANGUAGE FUNDAMENTALS · CHAPTER 08

Arrays
An array is a fixed-size, contiguous, index-based collection of elements of the same type, stored on the heap even though
the reference variable itself sits on the stack.

// Single-dimensional
int[] scores = {90, 85, 76, 92};

// Multi-dimensional
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
[Link](matrix[1][2]); // 6

// Common operations
int sum = 0;
for (int s : scores) sum += s;
[Link](scores);
[Link]([Link](scores));

MEMORY: int[] scores = {90, 85, 76, 92}

90 85 76 92
[0] [1] [2] [3]

Frequently Asked Array Problems


Find the second-largest element without sorting.
Reverse an array in place.
Find the missing number in 1..n.
Rotate an array left/right by k positions.
Find duplicate elements using a HashSet.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART II — LANGUAGE FUNDAMENTALS · CHAPTER 09

Strings, StringBuilder & StringBuffer


Strings Are Immutable
Once created, a String 's contents never change — operations like concat or toUpperCase return a new String object.
Immutability makes Strings safe to share, cache, and use as HashMap keys.

STRING POOL (INTERNING)

String a = "java"; // goes to the string pool


String b = "java"; // reuses the same pool reference
String c = new String("java"); // forces a new heap object

[Link](a == b); // true (same pool reference)


[Link](a == c); // false (different objects)
[Link]([Link](c)); // true (same content)

Common String Methods


Method Does

length(), charAt(i) Size & character access

substring(a,b), split(regex) Slice / tokenize

equals(), equalsIgnoreCase() Content comparison

trim(), replace(), toUpperCase() Transform, return new String

StringBuilder vs StringBuffer vs String


Type Mutable? Thread-Safe? Use When

String No Yes (immutable) Few or no modifications

StringBuilder Yes No Heavy concatenation, single-threaded (default choice)

StringBuffer Yes Yes (synchronized) Heavy concatenation across threads

INTERVIEW TIP
Never concatenate Strings with + inside a loop — each call allocates a new object. Use [Link]() instead; it's
a top "explain why this is slow" question.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART III — OBJECT-ORIENTED PROGRAMMING · CHAPTER 10

Classes, Objects & Constructors


A class is a blueprint; an object is a concrete instance of it, allocated on the heap with its own copy of instance fields.

public class Student {


String name;
int rollNo;

// Constructor
public Student(String name, int rollNo) {
[Link] = name;
[Link] = rollNo;
}

// Constructor overloading
public Student(String name) {
this(name, 0); // calls the other constructor
}
}

Student s1 = new Student("Asha", 12); // object creation

Constructor Rules
Same name as the class, no return type — not even void.
If you write none, Java supplies a no-arg default constructor; writing any constructor removes that default.
Constructor overloading: multiple constructors differing in parameter list, for flexible object creation.

MEMORY: Student s1 = new Student("Asha", 12)

Stack Heap (0x7f3a...)


s1 → 0x7f3a...
⟶ name = "Asha"
rollNo = 12

INTERVIEW TIP
"Can a constructor be private?" — yes, it's exactly how the Singleton pattern controls object creation.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART III — OBJECT-ORIENTED PROGRAMMING · CHAPTER 11

Encapsulation, Inheritance & Polymorphism


Encapsulation
Bundling data and the methods that operate on it, hiding internal fields behind private and exposing controlled access via
public getters/setters.

public class Account {


private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) {
if (amt > 0) balance += amt; // validation only possible via encapsulation
}
}

Inheritance
A subclass acquires fields/methods of a superclass using extends, enabling code reuse and "is-a" relationships. Java
supports single inheritance for classes (multiple via interfaces).

class Animal {
void eat() { [Link]("eats food"); }
}
class Dog extends Animal {
void bark() { [Link]("barks"); }
}
Dog d = new Dog();
[Link](); // inherited
[Link]();

Polymorphism
Type Resolved Example

Compile-time (static) At compile time Method overloading

Runtime (dynamic) At runtime, via the actual object type Method overriding

Animal a = new Dog(); // reference type Animal, object type Dog


[Link](); // which eat() runs depends on the OBJECT (runtime polymorphism)

INTERVIEW TIP

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


Dynamic method dispatch is resolved using the object's actual (runtime) type, not the reference's declared type — this is exactly
why overriding enables polymorphism and overloading does not.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART III — OBJECT-ORIENTED PROGRAMMING · CHAPTER 12

Abstraction & Interfaces


Abstract Classes
abstract class Shape {
abstract double area(); // no body — subclass must implement
void describe() { // can still have concrete methods
[Link]("Area = " + area());
}
}
class Circle extends Shape {
double radius;
Circle(double r) { radius = r; }
double area() { return [Link] * radius * radius; }
}

Interfaces
interface Payable {
double calculatePay(); // implicitly public abstract
default void printPay() { // Java 8+: default methods
[Link]("Pay: " + calculatePay());
}
}
class Employee implements Payable {
public double calculatePay() { return 50000; }
}

Abstract Class Interface

Can have constructors, instance fields Only constants (public static final)

Single inheritance (extends) A class can implement multiple interfaces

Mix of abstract & concrete methods Abstract + default + static methods (Java 8+)

INTERVIEW TIP
Since Java 8, interfaces can have default and static methods — a favorite "has this changed?" trap question for people who
learned Java pre-2014.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART III — OBJECT-ORIENTED PROGRAMMING · CHAPTER 13

Overloading, Overriding & Keywords


Overloading vs Overriding
Overloading Overriding

Same method name, different parameters Same signature, redefined in subclass

Same class Across parent/child classes

Resolved at compile time Resolved at runtime

static, final, this, super


Keyword Meaning

static Belongs to the class, not an instance — one copy shared by all objects

final Variable: constant; method: can't override; class: can't extend

this Refers to the current object instance

super Refers to the immediate parent class (fields, methods, constructor)

class Vehicle {
void honk() { [Link]("Generic honk"); }
}
class Car extends Vehicle {
static int wheels = 4; // static: shared by all Car objects
final String vin; // final: set once, never changed

Car(String vin) { [Link] = vin; } // this: disambiguate field vs param

@Override
void honk() {
[Link](); // super: call parent's version too
[Link]("Beep beep!");
}
}

COMMON MISTAKE
Overriding rules require the same method signature and a covariant or same return type — changing only the return type
incompatibly, or reducing visibility, breaks the override (and often just creates an overload by accident).

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART III — OBJECT-ORIENTED PROGRAMMING · CHAPTER 14

Packages & Access Modifiers


Packages
A package groups related classes/interfaces and prevents naming collisions — [Link] style.
Declared with package at the top of a file, used with import.

Access Modifiers
Modifier Same Class Same Package Subclass (diff pkg) World

public ✓ ✓ ✓ ✓

protected ✓ ✓ ✓ ✗

default (no modifier) ✓ ✓ ✗ ✗

private ✓ ✗ ✗ ✗

INTERVIEW TIP
Memorize this table exactly — "difference between protected and default" is one of the single most-repeated Core Java
interview questions.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART IV — CORE APIS & DATA STRUCTURES · CHAPTER 15

Wrapper Classes & Exception Handling


Wrapper Classes & Autoboxing
Every primitive has an object wrapper (int→Integer, double→Double...) so it can be used where objects are required —
Collections, generics. Autoboxing converts primitive→wrapper automatically; unboxing does the reverse.

List<Integer> nums = new ArrayList<>();


[Link](5); // autobox: int → Integer
int x = [Link](0); // unbox: Integer → int

Integer a = 127, b = 127;


[Link](a == b); // true (cached, -128..127)
Integer c = 200, d = 200;
[Link](c == d); // false (outside cache range, new objects)

Exception Handling
THROWABLE HIERARCHY

Throwable ⟶ Error (fatal, unrecoverable) / Exception

Checked (IOException, SQLException — must handle or declare) /

Unchecked / RuntimeException (NullPointerException, ArithmeticException)

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
} finally {
[Link]("Always runs — cleanup here");
}

// Custom exception
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String msg) { super(msg); }
}
void withdraw(double amt) throws InsufficientBalanceException {
if (amt > balance) throw new InsufficientBalanceException("Not enough funds");
}

INTERVIEW TIP

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


throw is used to actually raise an exception instance; throws is used in a method signature to declare what it might raise.
Mixing these up is an easy giveaway of shaky fundamentals.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART IV — CORE APIS & DATA STRUCTURES · CHAPTER 16

Collections — List, Set & Queue


THE COLLECTIONS FRAMEWORK (SIMPLIFIED)

Collection → List, Set, Queue | Map (separate hierarchy, not a Collection)

Type Ordered? Duplicates? Backing

ArrayList Insertion order Yes Dynamic array — fast random access

LinkedList Insertion order Yes Doubly linked list — fast insert/delete

HashSet No guarantee No Hash table

TreeSet Sorted No Red-black tree

PriorityQueue Priority order Yes Binary heap

List<String> names = new ArrayList<>([Link]("Zoe", "Amit", "Zoe"));


Set<String> unique = new HashSet<>(names); // dedupes: {Amit, Zoe}
Queue<Integer> pq = new PriorityQueue<>(); // min-heap by default
[Link](5); [Link](1); [Link](3);
[Link]([Link]()); // 1 (smallest first)

INTERVIEW TIP
"ArrayList vs LinkedList" — ArrayList wins for random access (O(1) get), LinkedList wins for frequent insert/delete in the middle
(O(1) once positioned, no shifting).

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART IV — CORE APIS & DATA STRUCTURES · CHAPTER 17

Collections — Map, Generics & Comparators


Map Implementations
Type Order Null Keys? Thread-Safe?

HashMap No guarantee One null key allowed No

TreeMap Sorted by key No No

LinkedHashMap Insertion order One null key No

Hashtable No guarantee No nulls at all Yes (legacy, synchronized)

Generics
Generics let classes/methods operate on typed parameters with compile-time type safety, removing the need for
manual casting.

class Box<T> {
private T value;
void set(T value) { [Link] = value; }
T get() { return value; }
}
Box<String> box = new Box<>();
[Link]("Hello"); // only Strings allowed — caught at compile time

Comparable vs Comparator
class Student implements Comparable<Student> {
int marks;
public int compareTo(Student o) { return [Link] - [Link]; } // natural order
}
[Link](students); // uses compareTo

// Comparator: custom / external ordering, doesn't touch the class


[Link]([Link](s -> [Link]));
[Link]([Link]((Student s) -> [Link]).reversed());

Comparable defines one natural ordering inside the class; Comparator lets you define many external orderings without
modifying the class.

INTERVIEW TIP
"Fail-fast vs fail-safe iterators" — HashMap/ArrayList iterators throw ConcurrentModificationException if the collection is
structurally modified during iteration (fail-fast); CopyOnWriteArrayList iterates a snapshot (fail-safe).

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART V — MEMORY & CONCURRENCY · CHAPTER 18

Memory Management & Garbage Collection


Stack vs Heap
STACK HEAP
Method calls, local variables, references All objects & arrays live here
One stack per thread Shared across all threads
LIFO, auto-cleared when method returns Managed & reclaimed by the Garbage Collector
Overflow → StackOverflowError Overflow → OutOfMemoryError

Garbage Collection
The GC automatically reclaims heap memory occupied by objects with no reachable references — no manual free() like
C/C++. The heap is generational:

Young Gen Old Gen


Eden + Survivor — Minor GC, frequent
⟶ survives ⟶ Long-lived objects — Major GC, rarer

Objects become eligible for GC when unreachable — e.g. reassigning the only reference, or the reference going out of
scope. [Link]() only suggests a collection; it's never guaranteed.

INTERVIEW TIP
"Can you force garbage collection?" — no. You can only request it via [Link](); the JVM decides if/when to actually run it.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART V — MEMORY & CONCURRENCY · CHAPTER 19

Multithreading & Concurrency


Creating Threads
// Option 1: extend Thread
class MyThread extends Thread {
public void run() { [Link]("Running"); }
}

// Option 2: implement Runnable (preferred — allows extending another class too)


class MyTask implements Runnable {
public void run() { [Link]("Running via Runnable"); }
}
new Thread(new MyTask()).start();

Thread Lifecycle

New ⟶ Runnable ⟶ Running ⟶ Blocked/Waiting ⟶ Terminated

Synchronization & Deadlock


public synchronized void withdraw(double amt) {
// only one thread can execute this on the same object at a time
balance -= amt;
}

Deadlock happens when two threads each hold a lock the other needs and wait forever — avoid it by always acquiring
locks in the same global order.

Inter-Thread Communication & Executors


wait()/notify()/notifyAll() coordinate threads waiting on the same object's monitor. In modern code, prefer the
Executor Framework over managing raw threads:

ExecutorService pool = [Link](4);


[Link](() -> [Link]("Task on a pooled thread"));
[Link]();

INTERVIEW TIP

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


Prefer Runnable + ExecutorService over manually extending Thread — it's the modern, more testable, resource-managed
approach interviewers want to hear.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART V — MEMORY & CONCURRENCY · CHAPTER 20

File Handling & Serialization


Reading & Writing Files
// Writing, with a BufferedWriter for efficiency
try (BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Placement prep in progress");
}

// Reading
try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
}

Try-with-resources (try (...) { }) auto-closes streams even if an exception occurs — always prefer it over manual
close() calls.

Serialization & Deserialization


Converting an object into a byte stream (to save to disk or send over a network) and back — implement the marker
interface Serializable .

class Student implements Serializable {


String name;
transient String password; // transient: skipped during serialization
}

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("[Link]"));


[Link](student);

ObjectInputStream in = new ObjectInputStream(new FileInputStream("[Link]"));


Student s = (Student) [Link]();

INTERVIEW TIP
Mark sensitive fields (passwords, secrets) transient so they're skipped during serialization — a common security-awareness
question.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VI — MODERN JAVA & ADVANCED TOPICS · CHAPTER 21

Java 8 Features
Lambda Expressions & Functional Interfaces
A functional interface has exactly one abstract method (e.g. Runnable, Comparator). A lambda is a compact way to
implement one inline.

@FunctionalInterface
interface Greeter { String greet(String name); }

Greeter g = name -> "Hello, " + name;


[Link]([Link]("Priya"));

// Method reference — shorthand for a lambda that just calls one method
List<String> names = [Link]("zoe", "amit");
[Link]([Link]::println);

Streams API
List<Integer> nums = [Link](4, 9, 2, 7, 6, 3);

List<Integer> result = [Link]()


.filter(n -> n % 2 == 0) // keep evens
.map(n -> n * n) // square them
.sorted() // ascending
.collect([Link]());
[Link](result); // [4, 16, 36]

Streams are lazy — intermediate ops (filter, map) don't run until a terminal op (collect, forEach, reduce) is called.

Optional & the Date/Time API


Optional<String> sc-camel-maybe-name = [Link](getName());
[Link]([Link]("Unknown")); // avoids null checks

LocalDate today = [Link]();


LocalDate deadline = [Link](30);
[Link]([Link](today, deadline).getDays());

INTERVIEW TIP
Java 8 is asked about constantly since it's the most common LTS baseline in industry — be fluent writing a filter→map→collect
stream pipeline live, on the spot.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VI — MODERN JAVA & ADVANCED TOPICS · CHAPTER 22

Inner Classes, Enums, Annotations & Reflection


Inner & Anonymous Classes
class Outer {
class Inner { void show() { [Link]("Inner class"); } } // needs an Outer instance
static class StaticNested { } // doesn't
}

Runnable r = new Runnable() { // anonymous class


public void run() { [Link]("Running anonymously"); }
};

Enums
enum Status {
PENDING, APPROVED, REJECTED;
}
Status s = [Link];
switch (s) {
case APPROVED -> [Link]("Go ahead");
default -> [Link]("Wait");
}

Enums are full classes under the hood — they can have fields, constructors, and methods, and are type-safe alternatives to
raw int/String constants.

Annotations & Reflection


Annotations (@Override, @Deprecated, @FunctionalInterface, custom ones) attach metadata read by the compiler or
at runtime. The Reflection API inspects and manipulates classes, fields, and methods at runtime — the mechanism
frameworks like Spring use to wire dependencies.

Class<?> clazz = [Link];


for (Field f : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}

INTERVIEW TIP
"Why do enums make good singletons?" — a single-element enum is a serialization-safe, thread-safe Singleton the JVM
guarantees is instantiated exactly once.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VI — MODERN JAVA & ADVANCED TOPICS · CHAPTER 23

Design Principles, SOLID & Best Practices


SOLID Principles
Letter Principle In One Line

S Single Responsibility A class should have one reason to change

O Open/Closed Open for extension, closed for modification

L Liskov Substitution Subtypes must be usable wherever the parent type is

I Interface Segregation Prefer many small interfaces over one bloated one

D Dependency Inversion Depend on abstractions, not concrete classes

Best Practices & Common Mistakes


Use equals()/hashCode() together and consistently — never override one without the other.
Favor immutability where possible (final fields, defensive copies).
Prefer interfaces as return/parameter types (List, not ArrayList) for flexibility.
Close resources with try-with-resources, never rely on GC to clean up file handles/sockets.
Avoid catching generic Exception/Throwable — catch specific types.
Don't use == to compare Strings/wrapper objects for content — use .equals().

Debugging & Performance Tips


Read the stack trace top-down — the first line is where the exception was thrown, not necessarily the root cause.
Use a debugger's breakpoints and "step over/into" rather than sprinkling [Link].
Prefer StringBuilder over String concatenation in loops; prefer ArrayList over LinkedList unless you truly need
O(1) middle inserts.
Set initial capacity on collections when the size is roughly known, to avoid repeated resizing.

INTERVIEW TIP
Even a one-line SOLID definition per letter, delivered confidently, outperforms a vague "it's about good design" answer —
interviewers are checking for structured thinking.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VII — PLACEMENT PREPARATION · CHAPTER 24

Interview Questions — Beginner & Intermediate


Beginner Level
Q: What is the difference between JDK, JRE, and JVM?
A: JDK = JRE + dev tools; JRE = JVM + libraries to run apps; JVM executes bytecode.

Q: Why is Java platform-independent?


A: It compiles to bytecode, which any JVM can execute regardless of the underlying OS/hardware.

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


A: == compares references (memory address) for objects, actual values for primitives; .equals() compares logical content and can be
overridden.

Q: What is a constructor, and can it be overloaded?


A: A special method (no return type, same name as class) that initializes objects; yes, multiple constructors with different parameter
lists are allowed.

Q: What is the difference between an array and an ArrayList?


A: Arrays are fixed-size and can hold primitives; ArrayList is resizable and holds objects only (autoboxed for primitives).

Intermediate Level
Q: Difference between abstract class and interface?
A: Abstract classes can have state and constructors and support single inheritance; interfaces only have constants (plus default/static
methods since Java 8) and support multiple inheritance.

Q: What happens if you don't override hashCode() when you override equals()?
A: Equal objects can end up with different hash codes, breaking their behavior in HashMap/HashSet — always override both together.

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


A: Checked (IOException) must be declared or caught at compile time; unchecked (RuntimeException) are not enforced by the
compiler.

Q: How does HashMap work internally?


A: Keys are hashed to buckets (an array of linked lists / red-black trees for large buckets since Java 8); collisions are chained within a
bucket.

Q: What is the diamond problem, and how does Java avoid it?
A: Ambiguity when a class inherits the same method from two parents; Java avoids it for classes by disallowing multiple inheritance,
and for interfaces requires the implementing class to explicitly resolve conflicting default methods.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VII — PLACEMENT PREPARATION · CHAPTER 25

Interview Questions — Advanced & Scenario-Based


Advanced Level
Q: How does the JVM decide which method to call in dynamic dispatch?
A: Via the object's virtual method table, resolved using the object's actual runtime type — not the reference's declared type.

Q: What is the difference between fail-fast and fail-safe iterators?


A: Fail-fast (ArrayList, HashMap) throw ConcurrentModificationException if the collection changes mid-iteration; fail-safe
(CopyOnWriteArrayList) iterate over a cloned snapshot instead.

Q: Explain the volatile keyword.


A: Guarantees visibility of a variable's latest value across threads by preventing caching in per-thread registers/CPU cache, but
doesn't provide atomicity for compound operations.

Q: How would you design a thread-safe Singleton?


A: Double-checked locking with a volatile instance field, or simplest and safest: a single-element enum.

Q: What's the difference between String pool interning and heap allocation for Strings?
A: Literals are interned into a shared pool for reuse; new String(...) forces a fresh heap object even with identical content, which is
why == can silently fail on them.

Scenario-Based Questions
Scenario: Your app throws OutOfMemoryError intermittently in production. How do you approach it?
A: Take a heap dump, analyze it (e.g. with a memory profiler) for retained object growth, look for unbounded caches/collections and
unclosed resources, then fix the leak or tune heap size.

Scenario: Two services update the same counter concurrently and results are wrong. What's happening and how do
you fix it?
A: A race condition from a non-atomic read-modify-write; fix with synchronized blocks, a Lock, or an AtomicInteger.

Scenario: You need to process a huge collection but only care about the first 5 matching results. How do you avoid
processing everything?
A: Use a Stream with filter().limit(5) — streams are lazy, so it short-circuits instead of evaluating the whole source.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VII — PLACEMENT PREPARATION · CHAPTER 26

Company-Wise Interview Questions


A snapshot of the flavor each company tends to favor in Core Java rounds — always still expect fundamentals (OOP,
collections, exceptions) everywhere.

TCS Infosys
OOP basics, String immutability, exception hierarchy, simple Collections (ArrayList vs LinkedList), constructors, access
coding (patterns, palindromes). modifiers, basic multithreading.

Wipro Cognizant
Static vs instance members, overloading vs overriding, simple Exception handling deep-dive, interfaces vs abstract classes,
SQL-Java integration questions. HashMap internals.

Accenture Capgemini
Core OOP with scenario framing ("design a library system"), Multithreading basics, generics, collection sorting with
basic design patterns. Comparator/Comparable.

Deloitte IBM
SOLID principles, clean-code practices, exception design in JVM internals, garbage collection tuning basics, concurrency
layered applications. (Executors, thread pools).

Amazon Microsoft
Data structures & algorithms in Java, LLD questions (design a Strong DSA + Java internals (memory model, GC), system
parking lot / rate limiter using OOP). design fundamentals for senior roles.

Google
Deep algorithmic problem solving, clean OOP design, edge-
case handling and complexity analysis.

INTERVIEW TIP
Service-based companies (TCS/Infosys/Wipro/Cognizant) weight fundamentals heavily; product companies
(Amazon/Microsoft/Google) weight DSA and design more — calibrate your prep time accordingly.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VIII — PRACTICE & REVISION · CHAPTER 27

Mini Projects & Real-World Use Cases


Build these as console applications to pull together OOP, collections, exceptions, and file handling in one place — exactly
what "tell me about a project" interview answers are made of.

Banking System
Account, SavingsAccount, CurrentAccount classes with inheritance; deposit/withdraw with custom
InsufficientBalanceException; transaction history in an ArrayList; persist accounts to a file.

Student Management System


CRUD on Student objects backed by a HashMap<Integer, Student> keyed by roll number; sort by marks with Comparator;
export a grade report.

Library Management System


Book and Member classes; issue/return workflow with due-date logic using the Date/Time API; interface-based Searchable
contract for title/author lookup.

Employee Management System


Abstract Employee base class, FullTime/Contract subclasses overriding calculatePay(); demonstrates polymorphism and
encapsulation end-to-end.

PLACEMENT TIP
Pick one project and go deep enough to defend every design decision — interviewers probe "why did you use a HashMap here,
not a List?" far more than they ask about the feature itself.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


PART VIII — PRACTICE & REVISION · CHAPTER 28

Cheatsheet, Roadmap & Placement Checklist


Quick-Revision Cheatsheet
Concept One-Line Recall

JVM/JRE/JDK JDK = JRE + tools; JRE = JVM + libraries

== vs equals() Reference vs content comparison

Overloading vs Overriding Compile-time same class vs runtime parent/child

Abstract class vs Interface State + single inheritance vs pure contract + multiple

ArrayList vs LinkedList Fast random access vs fast insert/delete

HashMap vs TreeMap Unordered O(1) vs sorted O(log n)

Checked vs Unchecked Compiler-enforced vs not

Stack vs Heap Method frames/locals vs objects

Comparable vs Comparator Natural order inside class vs external custom order

final / finally / finalize Constant / always-run block / pre-GC hook (deprecated)

Java Commands Reference


Command Purpose

javac [Link] Compile to bytecode (.class)

java File Run the compiled class

java -version Check installed Java version

jar cf [Link] *.class Package classes into a JAR

jshell Interactive REPL for quick experiments

Learning Roadmap
Foundations
Java basics, JVM/JRE/JDK, variables, operators, control flow, arrays, strings

Object-Oriented Programming
Classes, inheritance, polymorphism, abstraction, interfaces

Core APIs & Memory


Collections, generics, exceptions, memory model, garbage collection

Concurrency & Modern Java


Multithreading, Java 8 streams/lambdas, design principles

Placement-Ready
Interview questions, company-wise practice, mini projects, mock interviews — you're ready.

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT


Placement Preparation Checklist
☐ Can explain JVM/JRE/JDK and the compile-run pipeline without hesitation
☐ Comfortable writing OOP code from scratch — class, constructor, inheritance, interface
☐ Know when to use ArrayList vs LinkedList vs HashMap vs TreeMap vs HashSet
☐ Can explain exception handling and write a custom exception
☐ Can write a basic multithreaded program and explain synchronization
☐ Comfortable with a Java 8 stream pipeline (filter → map → collect)
☐ Have at least one mini project you can explain design decisions for, end-to-end
☐ Practiced company-specific question patterns for your target companies
☐ Reviewed this cheatsheet within 24 hours of your interview

CORE JAVA NOTES — PLACEMENT EDITION 0 → EXPERT

You might also like