These are the notes for Java episode 51, the last episode of the Java course. An interviewer asks "what does == compare?" and the confident answer "it checks if values are equal" is only half right. So instead of memorising answers, we prove each one by running code: == vs equals, equals without hashCode, why String is immutable, pass-by-value, the Integer cache and how a HashMap works inside. Then we walk the road to Spring Boot: a hard-wired class sends a paid SMS from a test, dependency injection fixes it, wiring 50 classes by hand hurts, and we write a 25-line IoC container with reflection: the core idea of Spring. Every compiler example was run with javac 21.
The problem: the question you thought you knew
Real-life problem. Your first Java interview. Fifty episodes of practice. The interviewer asks an easy one: "What does == compare?" You answer "whether two values are equal", and the interviewer writes a three-line program that prints false for two equal usernames.
Interviewers rarely want a memorised line. They want to see that you know why, and that you can show it.
How to answer any interview question: 4 steps
- Say it in one line. "
==compares references for objects;equalscompares content." - Say why. "Objects live on the heap; a variable holds a reference to one."
- Prove it with a tiny example. Two
Strings with the same text,==isfalse. - Name the trap and the fix. "Comparing
Strings with==passes some tests because of the string pool, then fails; useequals, known value first."
Step 4 is what makes an answer sound experienced.
Q1: == vs equals
Real-life example: two cups of the same chai.
| At the chai stall | In Java |
|---|---|
| "Is it the same cup?" | a == b: do both variables refer to the same object (identity)? |
| "Is it the same tea inside?" | a.equals(b): is the content the same (equality)? |
For primitives (int, double...) == compares the values. For objects it compares references. String.equals compares the characters.
A login check where typed arrives as a fresh object (as text from a form or a file does):
public class Main {
public static void main(String[] args) {
String typed = new String("admin"); // what the user typed
String saved = "admin"; // the saved username
System.out.println(typed == saved);
System.out.println(typed.equals(saved));
}
}
Output:
false
true
== refuses the correct username: two different objects. equals compares the characters.
The follow-up: null
public class Main {
static String typed; // nothing typed yet
public static void main(String[] args) {
System.out.println("admin".equals(typed));
System.out.println(typed.equals("admin"));
}
}
Output:
false
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "Main.typed" is null
at Main.main(Main.java:5)
You can't call a method on null. Put the known value first: "admin".equals(typed) is null-safe (it returns false). java.util.Objects.equals(a, b) is null-safe on both sides.
Q2: why override hashCode when you override equals?
Real-life example: the attendance register. R07 is marked present. Later the principal asks "is R07 here?" and the register says no, because it looked in the wrong section. A HashSet / HashMap first uses hashCode() to pick a bucket (the section), and only then calls equals inside that bucket.
import java.util.*;
class Student {
String roll;
Student(String roll) { this.roll = roll; }
@Override public boolean equals(Object o) {
return o instanceof Student s && s.roll.equals(roll);
}
}
public class Main {
public static void main(String[] args) {
Set<Student> present = new HashSet<>();
present.add(new Student("R07"));
System.out.println(new Student("R07").equals(new Student("R07")));
System.out.println(present.contains(new Student("R07")));
}
}
Output:
true
false
equals says the two students are equal, but contains can't find R07. We never wrote hashCode, so Object.hashCode() gives each object its own identity-based number; the set looks in the wrong bucket and never calls equals.
The fix is one line, built from the same field that equals uses:
import java.util.*;
class Student {
String roll;
Student(String roll) { this.roll = roll; }
@Override public boolean equals(Object o) {
return o instanceof Student s && s.roll.equals(roll);
}
@Override public int hashCode() { return roll.hashCode(); } // the fix
}
public class Main {
public static void main(String[] args) {
Set<Student> present = new HashSet<>();
present.add(new Student("R07"));
System.out.println(new Student("R07").equals(new Student("R07")));
System.out.println(present.contains(new Student("R07")));
}
}
Output:
true
true
The equals / hashCode contract
| Rule | Meaning |
|---|---|
a.equals(b) is true ⇒ a.hashCode() == b.hashCode() |
equal objects must land in the same bucket |
same hashCode does not mean equal |
different keys may share a hash: a collision, which is allowed |
| build both from the same fields | otherwise the first rule breaks |
hashCode must not change while the object is a key |
change a key's fields after put and the map can't find it |
The modern fix: a record (episode 24) generates equals, hashCode and toString from its fields.
Q3: why is String immutable?
Immutable means that once an object is created, its state can never change.
public class Main {
public static void main(String[] args) {
String name = "asha";
name.toUpperCase(); // result thrown away
System.out.println(name);
name = name.toUpperCase(); // keep the new String
System.out.println(name);
String a = "asha", b = "asha";
System.out.println(a == b); // one shared pool object
}
}
Output:
asha
ASHA
true
toUpperCase() did not change name; it returned a new String, which the first call threw away. And a == b is true because both literals share one object from the string pool (episode 9).
Why Java made String immutable:
| Reason | Explanation |
|---|---|
| String pool | sharing one object between many variables is only safe if nobody can change it |
| Security | a file path, URL or username is checked once and can't be changed afterwards |
Cached hashCode |
the hash is computed once and remembered, so strings are fast HashMap keys |
| Thread safety | threads can share strings without locks |
The trap: s += x in a loop builds a new String every time. Use StringBuilder (episode 10).
Q4: is Java pass-by-value or pass-by-reference?
Always pass-by-value. Java copies the argument into the parameter. For an object, the value copied is the reference (its address).
Real-life example: photocopies.
| In real life | In Java |
|---|---|
| a photocopy of your marks; your friend scribbles on it, your original is fine | an int passed in: a copy of the value |
| a photocopy of your address; your friend visits the house and paints it | an object passed in: a copy of the reference, the same object |
| your friend writes a new address on their photocopy; your house doesn't move | reassigning the parameter: the caller doesn't see it |
public class Main {
static void swap(int a, int b) { int t = a; a = b; b = t; }
static void addSurname(StringBuilder sb) { sb.append(" Sharma"); }
static void replace(StringBuilder sb) { sb = new StringBuilder("Ravi"); }
public static void main(String[] args) {
int x = 1, y = 2;
swap(x, y);
System.out.println(x + " " + y);
StringBuilder name = new StringBuilder("Asha");
addSurname(name);
replace(name);
System.out.println(name);
}
}
Output:
1 2
Asha Sharma
swap swapped copies. addSurname changed the shared object. replace only pointed its own copy of the reference somewhere else.
Q5: the Integer cache
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
}
}
Output:
true
false
true
Autoboxing (episode 28) turns Integer c = 128 into Integer.valueOf(128). valueOf returns cached objects for −128 to 127, so 127 gives the same object both times; 128 gives two new objects. Code that compares Integers with == passes tests with small numbers, then fails in production. Use equals (or compare ints).
Q6: how does HashMap work inside?
key "BB" → hashCode() = 2112 → spread: h ^ (h >>> 16) → & (n - 1) → bucket 0 of 16 → entries in that bucket → equals()
| Part | Detail |
|---|---|
| Buckets | an array of n buckets (16 by default, always a power of two) |
| Bucket index | (h ^ (h >>> 16)) & (n - 1): mix the high bits in, keep the low bits |
| Collision | two keys in one bucket: equals finds the right entry |
| Treeify | a bucket with 8+ entries (and a table of 64+) becomes a red-black tree: O(log n) even for bad hashes |
| Load factor | 0.75: when size > 75% of the buckets, the table doubles and entries are rehashed |
| Cost | get / put are O(1) on average |
Proving a collision: "Aa" and "BB" have the same hash code.
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Aa".hashCode() + " " + "BB".hashCode());
Map<String, Integer> m = new HashMap<>();
m.put("Aa", 1);
m.put("BB", 2); // same hash: a collision
System.out.println(m.get("Aa") + " " + m.get("BB") + ", size " + m.size());
int h = "BB".hashCode();
System.out.println("bucket out of 16: " + ((h ^ (h >>> 16)) & 15));
}
}
Output:
2112 2112
1 2, size 2
bucket out of 16: 0
Rapid-fire round
| Pair | One line each |
|---|---|
final / finally / finalize |
can't change (variable, method, class) · always runs after try · deprecated cleanup hook, don't use |
| checked vs unchecked | compiler forces you to catch or declare (IOException) · RuntimeException and below, it doesn't |
ArrayList vs LinkedList |
fast get(i), O(1) · fast add/remove at the ends; get(i) is O(n) |
| abstract class vs interface | shared state and code, one parent · a contract; a class can implement many |
String vs StringBuilder |
immutable · mutable, fast for building text (StringBuffer: synchronized) |
Comparable vs Comparator |
the natural order (compareTo, inside the class) · any order, from outside (compare) |
The road to Spring Boot
Real-life problem: the food delivery app grows up. Orders, payments, SMS alerts, 50 classes, and each one creates what it needs with new, inside itself. A unit test for placing an order sends a real, paid SMS.
Hard-wired: a paid SMS from a test
interface Notifier { void send(String to, String msg); }
class SmsNotifier implements Notifier {
public void send(String to, String msg) {
System.out.println("PAID SMS to " + to + ": " + msg);
}
}
class OrderService {
private final Notifier notifier = new SmsNotifier(); // hard-wired
void place(String phone) {
System.out.println("Order saved");
notifier.send(phone, "Your order is placed");
}
}
public class Main {
public static void main(String[] args) {
// a unit test: we only want to check place()
new OrderService().place("9800000001");
}
}
Output:
Order saved
PAID SMS to 9800000001: Your order is placed
OrderService chose its own part, so nothing outside can swap it.
Dependency injection
A dependency is an object your class needs to do its job. Dependency injection (DI) means the class doesn't create its dependencies; it receives them, usually in the constructor.
import java.util.*;
interface Notifier { void send(String to, String msg); }
class SmsNotifier implements Notifier {
public void send(String to, String msg) {
System.out.println("PAID SMS to " + to + ": " + msg);
}
}
class FakeNotifier implements Notifier { // for tests
List<String> sent = new ArrayList<>();
public void send(String to, String msg) { sent.add(to + ": " + msg); }
}
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; } // given from outside
void place(String phone) {
System.out.println("Order saved");
notifier.send(phone, "Your order is placed");
}
}
public class Main {
public static void main(String[] args) {
FakeNotifier fake = new FakeNotifier();
new OrderService(fake).place("9800000001"); // test
System.out.println("Test saw: " + fake.sent);
new OrderService(new SmsNotifier()).place("9800000001"); // real app
}
}
Output:
Order saved
Test saw: [9800000001: Your order is placed]
Order saved
PAID SMS to 9800000001: Your order is placed
Same OrderService, a FakeNotifier in the test and the real SmsNotifier in the app. Programming to the Notifier interface is what makes the swap possible.
The next problem: wiring 50 classes by hand
var repo = new OrderRepo(new Database(config));
var sms = new SmsNotifier(new HttpClient(), apiKey);
var orders = new OrderService(repo, sms, payments, ...);
// ...50 more lines, in the right order
Every constructor already says what it needs. So a program can read the constructors and do the wiring.
Invent a container
Reflection is Java looking at classes while the program runs: here, reading a class's constructor and its parameter types. Our container uses it, and recursion (episode 12) to build each dependency first:
import java.lang.reflect.Constructor;
import java.util.*;
interface Notifier { void send(String to, String msg); }
class SmsNotifier implements Notifier {
public void send(String to, String msg) { System.out.println("SMS to " + to + ": " + msg); }
}
class OrderRepo { void save() { System.out.println("Order saved"); } }
class OrderService {
private final OrderRepo repo; private final Notifier notifier;
OrderService(OrderRepo repo, Notifier notifier) { this.repo = repo; this.notifier = notifier; }
void place(String phone) { repo.save(); notifier.send(phone, "Order placed"); }
}
class Container { // our tiny "Spring"
private final Map<Class<?>, Class<?>> impls = new HashMap<>();
private final Map<Class<?>, Object> made = new HashMap<>();
void bind(Class<?> type, Class<?> impl) { impls.put(type, impl); }
<T> T get(Class<T> type) throws Exception {
if (made.containsKey(type)) return type.cast(made.get(type));
Class<?> c = impls.getOrDefault(type, type);
Constructor<?> ctor = c.getDeclaredConstructors()[0]; // reflection
Object[] deps = new Object[ctor.getParameterCount()];
for (int i = 0; i < deps.length; i++)
deps[i] = get(ctor.getParameterTypes()[i]); // make what it needs
Object obj = ctor.newInstance(deps);
System.out.println("made " + c.getSimpleName());
made.put(type, obj);
return type.cast(obj);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Container box = new Container();
box.bind(Notifier.class, SmsNotifier.class);
OrderService service = box.get(OrderService.class); // no "new"
service.place("9800000001");
}
}
Output:
made OrderRepo
made SmsNotifier
made OrderService
Order saved
SMS to 9800000001: Order placed
You just invented an IoC container. Inversion of control means your classes don't create or control their parts; the container does. That is the core of the Spring Framework. A real container adds much more: scopes, configuration, lifecycle callbacks, proxies, and detecting cycles (see the mini project).
The same idea in Spring Boot (preview)
This needs the Spring Boot libraries, so it was not run in this episode:
@SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
@Service
class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) { this.notifier = notifier; } // Spring passes it in
}
@RestController
class OrderController {
private final OrderService service;
OrderController(OrderService service) { this.service = service; }
@GetMapping("/orders/{id}")
String order(@PathVariable int id) { return "Order " + id + " is placed"; }
}
| Annotation | Meaning |
|---|---|
@SpringBootApplication |
starts Spring Boot: scans for components, auto-configures, starts the embedded web server |
@Service, @RestController |
"Spring, create and manage this object" (a bean) |
| constructor parameters | Spring injects the beans the constructor asks for |
@GetMapping("/orders/{id}") |
this method answers HTTP GET requests to that path |
@PathVariable |
takes id from the URL |
A REST API lets other programs talk to yours over HTTP (the web's request/response protocol), usually exchanging JSON. Spring Boot is Spring plus auto-configuration, an embedded server and "starter" dependencies, so a web service starts from one main method.
Your roadmap after core Java
Core Java (this course) → SQL + JDBC → Spring Boot (REST APIs) → Spring Data JPA → projects → apply
- SQL, to store data in a database, and JDBC, Java's standard API for talking to it.
- Spring Boot: REST controllers, services, configuration, validation, error handling.
- Spring Data JPA: maps database tables to Java objects (an ORM), so you write less SQL by hand.
- Alongside: DSA every day (two problems is enough), and Git, Maven/Gradle and JUnit (episodes 44-45) on every project.
- Build two real projects (for example a REST API with a database), put them on GitHub with a clear README, then apply. In the interview, explain your own code.
Common mistakes (and what you see)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
typed == saved for Strings |
no error: false for equal text |
== compares object identity |
typed.equals(saved) |
typed.equals("admin") when typed is null |
java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "Main.typed" is null |
a method called on null |
"admin".equals(typed) or Objects.equals |
equals overridden, hashCode not |
no error: contains() / get() miss |
the set looks in the wrong bucket | override both, or use a record |
name.toUpperCase(); on its own |
no error: name unchanged |
Strings are immutable | name = name.toUpperCase(); |
Integer c = 128, d = 128; c == d |
no error: false |
only −128..127 are cached | c.equals(d) |
a class doing new SmsNotifier() inside |
a paid SMS from a test | hard-wired dependency | constructor injection |
Most of these give no error at all. That's why interviewers love them.
Mini project: a container that refuses cycles
If A needs B and B needs A, our container would recurse forever (a StackOverflowError). Real containers detect this. Keep a stack of the classes being built right now; if one comes up again, it's a cycle:
import java.lang.reflect.Constructor;
import java.util.*;
class A { A(B b) {} }
class B { B(A a) {} } // A needs B, B needs A: a cycle
class Repo {}
class Service { Service(Repo r) {} }
class Container {
private final Map<Class<?>, Object> made = new HashMap<>();
private final Deque<Class<?>> building = new ArrayDeque<>(); // what we're making right now
<T> T get(Class<T> type) throws Exception {
if (made.containsKey(type)) return type.cast(made.get(type));
if (building.contains(type)) {
List<String> path = new ArrayList<>();
for (Iterator<Class<?>> it = building.descendingIterator(); it.hasNext(); )
path.add(it.next().getSimpleName());
path.add(type.getSimpleName());
throw new IllegalStateException("cycle: " + String.join(" -> ", path));
}
building.push(type);
Constructor<?> ctor = type.getDeclaredConstructors()[0];
Object[] deps = new Object[ctor.getParameterCount()];
for (int i = 0; i < deps.length; i++) deps[i] = get(ctor.getParameterTypes()[i]);
Object obj = ctor.newInstance(deps);
building.pop();
made.put(type, obj);
System.out.println("made " + type.getSimpleName());
return type.cast(obj);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Container box = new Container();
box.get(Service.class);
try {
box.get(A.class);
} catch (IllegalStateException e) {
System.out.println("Refused: " + e.getMessage());
}
}
}
Output:
made Repo
made Service
Refused: cycle: A -> B -> A
Practice
- Predict the output, then run it:
"Ja" + "va", a runtime concatenation, andintern(). - Make a
Seat(row, col)usable as aHashMapkey with the least code. - Write a
swapthat really swaps two elements of anint[], and explain why it works when theintswap didn't. - Homework: add a
Paymentinterface to our container and wireUpiPaymentintoOrderService. - Homework: test a
cancel()method with aFakeNotifier, including cancelling the same order twice.
Solution 1
public class Main {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Ja" + "va"; // two literals: joined at compile time
String s3 = "Ja";
String s4 = s3 + "va"; // joined at run time: a new object
System.out.println(s1 == s2);
System.out.println(s1 == s4);
System.out.println(s1 == s4.intern());
System.out.println(s1.equals(s4));
}
}
Output:
true
false
true
true
"Ja" + "va" is two literals, joined by the compiler into the pooled "Java". s3 + "va" is joined at run time into a new object. intern() returns the pooled copy.
Solution 2
import java.util.*;
record Seat(int row, int col) {} // equals and hashCode written for us
public class Main {
public static void main(String[] args) {
Map<Seat, String> booked = new HashMap<>();
booked.put(new Seat(3, 7), "Asha");
System.out.println(booked.get(new Seat(3, 7)));
System.out.println(new Seat(3, 7));
}
}
Output:
Asha
Seat[row=3, col=7]
A record generates equals and hashCode from row and col, and it is immutable, so the key can't change while it's in the map.
Solution 3
import java.util.Arrays;
public class Main {
static void swap(int[] arr, int i, int j) { // the array object is shared
int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
public static void main(String[] args) {
int[] marks = {40, 90};
swap(marks, 0, 1);
System.out.println(Arrays.toString(marks));
}
}
Output:
[90, 40]
The reference to the array is copied, but both copies point to the same array object, so changes to its elements are seen by the caller.
Solution 4
import java.lang.reflect.Constructor;
import java.util.*;
interface Payment { void charge(int rupees); }
class UpiPayment implements Payment {
public void charge(int rupees) { System.out.println("UPI charged Rs " + rupees); }
}
class OrderRepo { void save() { System.out.println("Order saved"); } }
class OrderService {
private final OrderRepo repo; private final Payment payment;
OrderService(OrderRepo repo, Payment payment) { this.repo = repo; this.payment = payment; }
void place(int rupees) { payment.charge(rupees); repo.save(); }
}
class Container {
private final Map<Class<?>, Class<?>> impls = new HashMap<>();
private final Map<Class<?>, Object> made = new HashMap<>();
void bind(Class<?> type, Class<?> impl) { impls.put(type, impl); }
<T> T get(Class<T> type) throws Exception {
if (made.containsKey(type)) return type.cast(made.get(type));
Class<?> c = impls.getOrDefault(type, type);
Constructor<?> ctor = c.getDeclaredConstructors()[0];
Object[] deps = new Object[ctor.getParameterCount()];
for (int i = 0; i < deps.length; i++) deps[i] = get(ctor.getParameterTypes()[i]);
Object obj = ctor.newInstance(deps);
made.put(type, obj);
return type.cast(obj);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Container box = new Container();
box.bind(Payment.class, UpiPayment.class);
box.get(OrderService.class).place(250);
}
}
Output:
UPI charged Rs 250
Order saved
Solution 5
import java.util.*;
interface Notifier { void send(String to, String msg); }
class FakeNotifier implements Notifier {
List<String> sent = new ArrayList<>();
public void send(String to, String msg) { sent.add(to + ": " + msg); }
}
class OrderService {
private final Notifier notifier;
private final Set<Integer> open = new HashSet<>(Set.of(7));
OrderService(Notifier notifier) { this.notifier = notifier; }
void cancel(int id, String phone) {
if (!open.remove(id)) throw new IllegalArgumentException("no open order " + id);
notifier.send(phone, "Order " + id + " cancelled");
}
}
public class Main {
public static void main(String[] args) {
FakeNotifier fake = new FakeNotifier();
OrderService service = new OrderService(fake);
service.cancel(7, "9800000001");
System.out.println(fake.sent.equals(List.of("9800000001: Order 7 cancelled")) ? "PASS" : "FAIL " + fake.sent);
try {
service.cancel(7, "9800000001");
System.out.println("FAIL: no exception");
} catch (IllegalArgumentException e) {
System.out.println("PASS: " + e.getMessage());
}
}
}
Output:
PASS
PASS: no open order 7
Quick quiz
Integer p = 100, q = 100;
Integer r = 500, s = 500;
System.out.println((p == q) + " " + (r == s));
A) true true B) true false C) false false D) false true
Answer
B: true false. Autoboxing uses Integer.valueOf, which returns cached objects for −128 to 127. 100 is cached (same object); 500 is not (two objects). Compare with equals.
Interview questions
What is the difference between == and equals()?
For objects, == checks whether two references point to the same object; equals checks logical equality as the class defines it (String compares characters). Object.equals defaults to ==. For primitives, == compares values.
Why must hashCode be overridden with equals?
Hash-based collections find the bucket with hashCode before calling equals. If equal objects have different hash codes, contains/get look in the wrong bucket and miss. Contract: equal objects ⇒ equal hash codes.
Why is String immutable? What is the string pool?
The pool lets identical literals share one object, which is only safe if nobody can change it. Immutability also gives security (checked values can't change), a cached hashCode and thread safety. The pool is an area of the heap holding one copy of each literal; intern() returns the pooled copy.
Is Java pass-by-value or pass-by-reference?
Always pass-by-value. For objects the value copied is the reference, so a method can change the object's state but cannot make the caller's variable point to a different object.
Explain how HashMap works internally.
An array of buckets; the key's hashCode is spread and masked to a bucket index; collisions share a bucket and equals picks the entry; 8+ entries in a bucket turn into a red-black tree; past the load factor (0.75) the table doubles and rehashes. Average O(1) get/put. One null key is allowed; it is not thread-safe (ConcurrentHashMap is).
What is dependency injection, and why use it?
A class receives its dependencies (usually through its constructor) instead of creating them. It decouples the class from concrete implementations, so you can swap a fake in tests or a different implementation in production, and it makes dependencies visible in the constructor.
What is IoC, and how does Spring use it?
Inversion of control: the framework, not your code, creates and wires objects. Spring's IoC container (the ApplicationContext) creates beans, reads what each constructor needs, injects them, and manages their lifecycle.
What is the difference between Spring and Spring Boot?
Spring is the framework (IoC container, web MVC, data access...). Spring Boot sits on top: auto-configuration, starter dependencies, an embedded server and sensible defaults, so an application runs from one main method with little configuration.
Glossary
| Term | Meaning | Example |
|---|---|---|
Identity (== on objects) |
whether two references point to the same object | new String("admin") == "admin" is false |
Equality (equals) |
whether two objects have the same content, as the class defines it | "admin".equals(typed) |
| Null-safe | does not throw when a value is null |
known value first |
NullPointerException |
thrown when you use a null reference as an object |
typed.equals(...) with typed == null |
hashCode |
an int that hash collections use to pick a bucket |
"BB".hashCode() is 2112 |
| Bucket | one slot of a hash table's array, holding entries with the same index | bucket 0 of 16 |
| Collision | two different keys in the same bucket (often the same hash) | "Aa" and "BB" |
| equals/hashCode contract | equal objects must have equal hash codes | build both from the same fields |
| Immutable | can't change after creation | String |
| String pool | heap area with one shared copy of each string literal | "asha" == "asha" is true |
intern() |
returns the pooled copy of a string | s4.intern() |
| Pass-by-value | the method gets a copy of the argument's value | swap(int, int) does nothing |
| Reference | the value that points to an object | the "address on the photocopy" |
| Autoboxing | automatic conversion from a primitive to its wrapper | Integer c = 128 |
| Integer cache | Integer.valueOf reuses objects for −128..127 |
127 == 127 is true |
| Load factor | how full a HashMap may get before it resizes (0.75) |
12 entries in 16 buckets |
| Treeify | turning a crowded bucket into a red-black tree | 8+ entries in one bucket |
| Dependency | an object your class needs to do its job | Notifier for OrderService |
| Hard-wired | a class creates its own dependency with new |
= new SmsNotifier() in a field |
| Dependency injection (DI) | giving a class its dependencies from outside | new OrderService(fake) |
| Fake | a simple stand-in implementation used in tests | FakeNotifier |
| Reflection | inspecting classes, constructors and methods while the program runs | getDeclaredConstructors() |
| IoC container | an object that creates and wires other objects for you | our Container, Spring's ApplicationContext |
| Inversion of control (IoC) | the framework controls object creation, not your code | Spring |
| Bean | an object created and managed by Spring | a @Service class |
| Spring Boot | Spring plus auto-configuration, starters and an embedded server | @SpringBootApplication |
| REST API | an interface other programs call over HTTP, usually with JSON | GET /orders/7 |
| HTTP | the web's request/response protocol | GET, POST |
| JDBC | Java's standard API for talking to relational databases | DriverManager.getConnection |
| JPA / ORM | mapping database tables to Java objects | Spring Data JPA |
Summary
- Answer in 4 steps: one line, why, proof, the trap.
==is identity for objects,equalsis content; write"known".equals(x)to be null-safe.- Override
equalsandhashCodetogether (or use a record): hash collections look in the bucket first. Stringis immutable (pool, security, cached hash, thread safety); its methods return new strings.- Java is always pass-by-value; for objects the reference is copied.
Integercaches −128..127: compare wrappers withequals.HashMap: buckets by hash,equalsinside, treeify at 8, resize at 0.75, O(1) average.- Dependency injection + an IoC container is the heart of Spring; Spring Boot adds auto-configuration and an embedded server.
- Next: SQL and JDBC, then Spring Boot, and daily DSA practice. This is the end of the Java course. Well done!