# Java Backend Revision Notes
**For: Fluency-level understanding (not depth)**
**Goal: Quick reference while building Spring Boot projects**
---
## Table of Contents
1. [Java Basics](#java-basics)
2. [Variables & Data Types](#variables--data-types)
3. [Operators](#operators)
4. [Control Flow](#control-flow)
5. [Methods](#methods)
6. [Classes & Objects](#classes--objects)
7. [Strings](#strings)
8. [Collections (ArrayList, HashMap)](#collections-arraylist-hashmap)
9. [Exception Handling](#exception-handling)
10. [Access Modifiers](#access-modifiers)
11. [Spring Boot Annotations](#spring-boot-annotations)
12. [Common Patterns](#common-patterns)
13. [Quick Syntax Reference](#quick-syntax-reference)
---
## Java Basics
### What is Java?
- **Compiled language**: Code → Bytecode → JVM runs it
- **Object-oriented**: Everything is a class or object
- **Platform-independent**: Write once, run anywhere (JVM handles the rest)
- **Strongly typed**: Every variable has a type, checked at compile time
### Running Java
```bash
# Write code
javac [Link] # Compile to bytecode
java HelloWorld # Run the bytecode
# Spring Boot (easier)
mvn spring-boot:run # Runs your application
```
### Basic Structure
```java
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
```
- `public` = accessible from anywhere
- `class` = blueprint for objects
- `static` = belongs to the class, not instances
- `void` = doesn't return anything
- `main()` = entry point (where code starts)
---
## Variables & Data Types
### Primitive Types (Built-in)
```java
int age = 25; // Whole numbers (-2B to 2B)
long big = 10000000000L; // Larger whole numbers (suffix: L)
float price = 19.99f; // Decimal (32-bit, suffix: f)
double salary = 50000.50; // Decimal (64-bit, default for decimals)
boolean isActive = true; // true or false only
char letter = 'A'; // Single character (must use single quotes)
byte tiny = 127; // Very small numbers (-128 to 127)
short medium = 32000; // Between int and byte
```
### Reference Types (Objects)
```java
String name = "Shraddha"; // Text (objects, not primitives)
ArrayList<Integer> numbers = new ArrayList<>(); // Collection
Job job = new Job(); // Custom class instance
```
**Key difference:** Primitives store values, references store memory addresses.
### Variable Declaration Rules
```java
int x = 10; // Declared and initialized
int y; // Declared only (can't use until initialized)
y = 20; // Initialized
final int CONSTANT = 100; // Cannot change after set (convention: ALL_CAPS)
```
---
## Operators
### Arithmetic
```java
int a = 10, b = 3;
a + b // 13
a - b // 7
a * b // 30
a / b // 3 (integer division)
a % b // 1 (remainder)
a++ // a becomes 11, post-increment
++a // a becomes 11, pre-increment
```
### Comparison (return boolean)
```java
5 == 5 // true (equal to)
5 != 3 // true (not equal)
5 > 3 // true (greater than)
5 >= 5 // true (greater than or equal)
5 < 10 // true (less than)
```
### Logical
```java
true && false // AND (both must be true)
true || false // OR (at least one true)
!true // NOT (flips boolean)
```
### Assignment
```java
x = 10; // Assign
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2; // x = x * 2
x /= 4; // x = x / 4
```
---
## Control Flow
### If/Else
```java
int age = 20;
if (age >= 18) {
[Link]("Adult");
} else if (age >= 13) {
[Link]("Teen");
} else {
[Link]("Child");
}
// Ternary (one-liner if/else)
String status = age >= 18 ? "Adult" : "Child";
```
### Switch
```java
String day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of week");
break; // Important! Prevents fall-through
case "Friday":
[Link]("Almost weekend");
break;
default:
[Link]("Other day");
}
```
### For Loop
```java
// Traditional for loop
for (int i = 0; i < 5; i++) {
[Link](i); // Prints 0, 1, 2, 3, 4
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
[Link](num);
}
// For ArrayList
ArrayList<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
for (String name : names) {
[Link](name);
}
```
### While Loop
```java
int count = 0;
while (count < 5) {
[Link](count);
count++;
}
// Do-while (executes at least once)
do {
[Link]("Runs once even if condition is false");
} while (false);
```
### Break & Continue
```java
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit loop immediately
}
if (i == 2) {
continue; // Skip to next iteration
}
[Link](i); // Prints: 0, 1, 3, 4
}
```
---
## Methods
### Method Definition
```java
// Syntax: [access] [return-type] methodName([parameters]) { body }
public int add(int a, int b) {
int sum = a + b;
return sum; // Must return int (matches return type)
}
public void greet(String name) {
[Link]("Hello, " + name);
// No return statement (void means returns nothing)
}
public String getName() {
return "Shraddha"; // Returns a String
}
private boolean isValid(int age) {
return age >= 0 && age <= 150; // Returns boolean
}
```
### Calling Methods
```java
int result = add(5, 3); // Calls add method, stores result
greet("Shraddha"); // Calls greet method
String name = getName(); // Calls getName, stores result
boolean valid = isValid(25); // Calls isValid, stores result
```
### Method Overloading (Same name, different parameters)
```java
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public String add(String a, String b) {
return a + b; // Concatenates strings
}
// Java picks the right one based on parameters
add(5, 3); // Calls first (int parameters)
add(5.5, 3.2); // Calls second (double parameters)
add("Hello ", "World"); // Calls third (String parameters)
```
### Variable Scope
```java
public class Example {
public int classVariable = 10; // Accessible in all methods of this class
public void myMethod() {
int localVariable = 5; // Only accessible inside this method
[Link](localVariable); // Works
}
public void anotherMethod() {
[Link](localVariable); // ERROR! Not accessible here
}
}
```
---
## Classes & Objects
### Class Definition
```java
public class Job {
// Properties (variables)
public String title;
public String company;
public int salary;
// Constructor (initializes an object)
public Job(String title, String company) {
[Link] = title; // this = current object
[Link] = company;
}
// Method
public void printDetails() {
[Link](title + " at " + company);
}
}
```
### Creating Objects
```java
// new = create a new instance in memory
// Job() = constructor to initialize it
Job job1 = new Job("Backend Dev", "Grab");
Job job2 = new Job("Data Scientist", "PhonePe");
[Link](); // Output: Backend Dev at Grab
[Link](); // Output: Data Scientist at PhonePe
```
### Constructors
```java
public class User {
public String name;
public int age;
// No-argument constructor
public User() {
[Link] = "Unknown";
[Link] = 0;
}
// Constructor with parameters
public User(String name, int age) {
[Link] = name;
[Link] = age;
}
}
// Usage
User user1 = new User(); // Uses no-arg constructor
User user2 = new User("Shraddha", 20); // Uses parameterized constructor
```
### Inheritance
```java
// Parent class
public class Animal {
public void eat() {
[Link]("Eating...");
}
}
// Child class (inherits from Animal)
public class Dog extends Animal {
public void bark() {
[Link]("Woof!");
}
}
// Usage
Dog dog = new Dog();
[Link](); // Inherited from Animal
[Link](); // Own method
```
### This Keyword
```java
public class Person {
public String name;
public Person(String name) {
[Link] = name; // [Link] = parameter name (avoids confusion)
}
public Person copy() {
return new Person([Link]); // this = current object
}
}
```
---
## Strings
### Creating Strings
```java
String s1 = "Hello"; // String literal
String s2 = new String("Hello"); // Using constructor (rare)
// String concatenation
String greeting = "Hello" + " " + "World"; // "Hello World"
String name = "Shraddha";
String message = "Hi, " + name; // "Hi, Shraddha"
```
### String Methods
```java
String s = "Java";
[Link](); // 4 (number of characters)
[Link](0); // 'J' (character at index 0)
[Link](1); // "ava" (from index 1 to end)
[Link](1, 3); // "av" (from index 1 to 3, exclusive)
[Link](); // "JAVA"
[Link](); // "java"
[Link](); // Removes leading/trailing spaces
[Link]("av"); // true (if string contains "av")
[Link]("Ja"); // true
[Link]("va"); // true
[Link]("a", "o"); // "Jovo" (replace all occurrences)
[Link](","); // Splits by delimiter, returns array
[Link]("Java"); // true (compare strings)
[Link]("java"); // true (ignore case)
```
### Important: String Immutability
```java
String s = "Hello";
s = s + " World"; // Creates new String object, doesn't modify original
// Old "Hello" is discarded
// For many concatenations, use StringBuilder
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link](" ");
[Link]("World");
String result = [Link](); // "Hello World"
```
### Comparing Strings
```java
String a = "Java";
String b = "Java";
String c = new String("Java");
a == b; // true (same reference in memory due to string pool)
a == c; // false (different objects)
[Link](b); // true (compares content)
[Link](c); // true (compares content)
// Always use .equals() for string comparison, not ==
```
---
## Collections: ArrayList & HashMap
### ArrayList (Ordered, allows duplicates)
```java
// Declaration
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Job> jobs = new ArrayList<>();
// Add elements
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
// Access elements
String first = [Link](0); // "Alice"
int size = [Link](); // 3
// Modify elements
[Link](0, "Alicia"); // Changes "Alice" to "Alicia"
// Remove elements
[Link](0); // Removes "Alicia"
[Link]("Bob"); // Removes "Bob"
[Link](); // Removes all
// Check if contains
boolean has = [Link]("Charlie"); // true/false
// Iterate through ArrayList
for (String name : names) {
[Link](name);
}
// Or with index
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
```
### HashMap (Key-Value pairs, no order)
```java
// Declaration
HashMap<String, Integer> ageMap = new HashMap<>();
HashMap<String, String> phonebook = new HashMap<>();
HashMap<Integer, Job> jobsById = new HashMap<>();
// Add key-value pairs
[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 28);
// Access by key
int aliceAge = [Link]("Alice"); // 25
String unknown = [Link]("David"); // null (key doesn't exist)
// Check if key exists
boolean has = [Link]("Alice"); // true
boolean hasValue = [Link](25); // true
// Modify value
[Link]("Alice", 26); // Updates Alice's age
// Remove
[Link]("Bob"); // Removes Bob's entry
[Link](); // Removes all
// Iterate through HashMap
for (String name : [Link]()) {
int age = [Link](name);
[Link](name + " is " + age);
}
// Or get all entries
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}
```
### ArrayList vs HashMap
| Feature | ArrayList | HashMap |
|---------|-----------|---------|
| **Order** | Yes (maintains insertion order) | No |
| **Access** | By index (0, 1, 2...) | By key |
| **Duplicates** | Allowed | Keys must be unique |
| **Use case** | List of items | Mapping keys to values |
---
## Exception Handling
### Try-Catch
```java
try {
int result = 10 / 0; // This throws ArithmeticException
[Link](result);
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
[Link](); // Prints stack trace for debugging
}
// Multiple catch blocks
try {
int[] arr = new int[5];
arr[10] = 5; // This throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index out of range");
} catch (Exception e) { // Catches any exception (catch-all)
[Link]("Some error occurred");
}
```
### Try-Catch-Finally
```java
try {
// Code that might throw exception
File file = new File("[Link]");
// Use file
} catch (FileNotFoundException e) {
[Link]("File not found");
} finally {
// Runs regardless of whether exception occurred
[Link]("Cleanup code here");
}
```
### Throwing Exceptions
```java
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
// Caller must handle it
try {
int result = divide(10, 0);
} catch (IllegalArgumentException e) {
[Link]([Link]()); // "Divisor cannot be zero"
}
```
### Common Exceptions
| Exception | When thrown | Example |
|-----------|------------|---------|
| `NullPointerException` | Accessing null object | `String s = null; [Link]();` |
| `ArrayIndexOutOfBoundsException` | Invalid array index | `arr[100]` when [Link] = 5 |
| `ArithmeticException` | Invalid arithmetic | `10 / 0` |
| `NumberFormatException` | Invalid number parsing | `[Link]("abc")` |
| `IllegalArgumentException` | Invalid argument to method | Custom validation |
---
## Access Modifiers
Control who can access your code.
### The Four Levels
```java
public class MyClass {
public int x = 1; // Accessible from anywhere
protected int y = 2; // Accessible in same package + subclasses
int z = 3; // Default (no modifier): same package only
private int w = 4; // Accessible only in this class
}
// Usage from outside package
MyClass obj = new MyClass();
obj.x = 10; // OK
obj.y = 20; // ERROR (not same package)
obj.z = 30; // ERROR (not same package)
obj.w = 40; // ERROR (private)
```
### For Methods and Classes
```java
public class Public {
// Can be accessed from anywhere
}
class Default {
// Can be accessed only from same package
}
public class Example {
public void publicMethod() {
// Accessible from anywhere
}
protected void protectedMethod() {
// Accessible in same package + subclasses
}
void defaultMethod() {
// Accessible in same package only
}
private void privateMethod() {
// Accessible only in this class
}
}
```
### Best Practices
- **public**: Only for things others need to use
- **private**: For internal implementation
- **protected**: For subclasses to override
- **default**: Rarely used, avoid
---
## Spring Boot Annotations
These are special markers that tell Spring Boot what to do.
### @RestController
```java
@RestController // This class handles HTTP requests
@RequestMapping("/jobs") // All endpoints start with /jobs
public class JobController {
@GetMapping // Handles GET /jobs
public List<Job> getAllJobs() {
return [Link]();
}
@PostMapping // Handles POST /jobs
public Job createJob(@RequestBody Job job) {
return [Link](job);
}
}
```
### @Service
```java
@Service // This class contains business logic
public class JobService {
@Autowired // Spring injects JobRepository
private JobRepository jobRepo;
public List<Job> getAllJobs() {
return [Link](); // Queries database
}
public Job save(Job job) {
return [Link](job);
}
}
```
### @Repository
```java
@Repository // This class handles database access
public interface JobRepository extends JpaRepository<Job, UUID> {
// JpaRepository provides standard CRUD methods:
// findAll(), findById(), save(), delete(), etc.
}
```
### @Entity
```java
@Entity // This class represents a database table
@Table(name = "jobs") // Table name in database
public class Job {
@Id // Primary key
@GeneratedValue(strategy = [Link])
private UUID id;
@Column(name = "job_title") // Column name in database
private String title;
private String company; // No @Column = uses field name as column
}
```
### @Autowired
```java
@Service
public class JobService {
@Autowired // Spring automatically creates and injects
private JobRepository jobRepo;
// jobRepo is now ready to use, no need for new JobRepository()
}
```
### Request Mappings
```java
@RestController
@RequestMapping("/api/jobs")
public class JobController {
@GetMapping // GET /api/jobs
public List<Job> getAll() { }
@GetMapping("/{id}") // GET /api/jobs/{id}
public Job getById(@PathVariable UUID id) { }
@PostMapping // POST /api/jobs
public Job create(@RequestBody Job job) { }
@PutMapping("/{id}") // PUT /api/jobs/{id}
public Job update(@PathVariable UUID id, @RequestBody Job job) { }
@DeleteMapping("/{id}") // DELETE /api/jobs/{id}
public void delete(@PathVariable UUID id) { }
}
```
### Request/Response Annotations
```java
@PostMapping
public Job create(
@RequestBody Job job, // Parse JSON body as Job object
@RequestParam String status, // Query parameter: ?status=applied
@PathVariable UUID id // Path parameter: /jobs/{id}
){
return [Link](job);
}
```
---
## Common Patterns
### MVC Architecture (Model-View-Controller)
```
Client (Browser)
↓ HTTP Request
Controller (receives request, calls service)
↓
Service (business logic, calls repository)
↓
Repository (database access)
↓ Database
(Reverse path for response)
```
### Dependency Injection
```java
// BAD: Creating objects yourself
@Service
public class JobService {
private JobRepository repo = new JobRepository(); // Tight coupling
}
// GOOD: Spring injects dependencies
@Service
public class JobService {
@Autowired
private JobRepository repo; // Spring creates and injects
// Loose coupling, easier to test
}
```
### DTO (Data Transfer Object)
```java
// Used to transfer data between layers
public class JobDTO {
public UUID id;
public String title;
public String company;
// Only fields we want to expose to client
}
// Entity (database representation)
@Entity
public class Job {
@Id
private UUID id;
@Column
private String title;
@Column
private String company;
@Column
private String internalNotes; // Don't expose this to client
}
```
### Null Checking
```java
// BAD: Causes NullPointerException if user is null
User user = [Link](id);
[Link]([Link]());
// GOOD: Check before using
User user = [Link](id);
if (user != null) {
[Link]([Link]());
}
// BEST: Use Optional (Java 8+)
Optional<User> user = [Link](id);
if ([Link]()) {
[Link]([Link]().getName());
}
```
---
## Quick Syntax Reference
### Variable Declaration
```java
int age = 25;
String name = "Shraddha";
ArrayList<String> list = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
final int CONSTANT = 100;
```
### Method Syntax
```java
[access] [return-type] methodName([parameters]) {
// body
return value; // if return-type is not void
}
public void greet(String name) {
[Link]("Hello, " + name);
}
private int add(int a, int b) {
return a + b;
}
```
### Class Syntax
```java
public class ClassName {
// Properties
private String property;
// Constructor
public ClassName(String property) {
[Link] = property;
}
// Getter
public String getProperty() {
return property;
}
// Setter
public void setProperty(String property) {
[Link] = property;
}
// Method
public void doSomething() {
[Link](property);
}
}
```
### If-Else
```java
if (condition) {
// code
} else if (other condition) {
// code
} else {
// code
}
```
### For Loop
```java
for (int i = 0; i < 10; i++) {
[Link](i);
}
for (String item : list) {
[Link](item);
}
```
### Try-Catch
```java
try {
// code that might fail
} catch (ExceptionType e) {
// handle exception
}
```
### ArrayList Operations
```java
ArrayList<String> list = new ArrayList<>();
[Link]("item");
[Link](0);
[Link](0);
[Link]();
[Link]();
for (String item : list) { }
```
### HashMap Operations
```java
HashMap<String, Integer> map = new HashMap<>();
[Link]("key", value);
[Link]("key");
[Link]("key");
[Link]("key");
[Link]();
for (String key : [Link]()) { }
```
### String Operations
```java
String s = "Hello";
[Link]();
[Link](0);
[Link](1);
[Link]();
[Link]();
[Link]("ell");
[Link]("Hello");
[Link]("H", "J");
```
---
## Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---------|---------|-----|
| Using `==` for strings | Compares references, not content | Use `.equals()` |
| Forgetting `new` | Can't create objects | `new ClassName()` |
| Array index out of bounds | Accessing invalid index | Check length first |
| Null pointer exception | Using null object | Check if null before use |
| Forgetting `break` in switch | Fall-through to next case | Always use `break` |
| Modifying list while iterating | Concurrent modification error | Use iterator or create copy |
| Forgetting return statement | Method doesn't return value | Add `return` statement |
| Comparing objects with `==` | Compares references | Use `.equals()` |
---
## Cheat Sheet for Spring Boot Backend
### Create a REST Endpoint
```java
@RestController
@RequestMapping("/api/jobs")
public class JobController {
@Autowired
private JobService jobService;
@GetMapping
public List<Job> getAllJobs() {
return [Link]();
}
@PostMapping
public Job createJob(@RequestBody Job job) {
return [Link](job);
}
}
```
### Create a Service
```java
@Service
public class JobService {
@Autowired
private JobRepository jobRepo;
public List<Job> getAll() {
return [Link]();
}
public Job save(Job job) {
return [Link](job);
}
}
```
### Create a Repository
```java
@Repository
public interface JobRepository extends JpaRepository<Job, UUID> {
// findAll(), findById(), save(), delete() provided by JpaRepository
}
```
### Create an Entity
```java
@Entity
@Table(name = "jobs")
public class Job {
@Id
@GeneratedValue(strategy = [Link])
private UUID id;
@Column
private String title;
@Column
private String company;
// Constructor
public Job(String title, String company) {
[Link] = title;
[Link] = company;
}
// Getters/Setters (can generate in IDE)
public String getTitle() { return title; }
public void setTitle(String title) { [Link] = title; }
public String getCompany() { return company; }
public void setCompany(String company) { [Link] = company; }
}
```
---
## Interview Quick-Fire Answers
**Q: What's the difference between `int` and `Integer`?**
A: `int` is primitive (stores value), `Integer` is object (stores reference). Use `int` for performance,
`Integer` when you need null or collections.
**Q: Why use ArrayList instead of Array?**
A: ArrayList can grow/shrink dynamically, Array is fixed size. ArrayList is more flexible.
**Q: What does `new` do?**
A: Creates a new object in memory and calls the constructor to initialize it.
**Q: What's the difference between `==` and `.equals()`?**
A: `==` compares references (memory address), `.equals()` compares content (values).
**Q: What does `@Autowired` do?**
A: Tells Spring to automatically create and inject a dependency (object) into the field.
**Q: What's a constructor?**
A: A special method that initializes an object when it's created with `new`.
**Q: What's the difference between checked and unchecked exceptions?**
A: Checked exceptions must be caught (FileNotFoundException). Unchecked exceptions don't
have to be (NullPointerException).
**Q: What does `public` mean?**
A: The code can be accessed from anywhere (other classes, other packages).
**Q: What's the difference between `null` and not initialized?**
A: `null` is a value meaning "no object", not initialized means variable doesn't have a value yet
(error to use).
**Q: How do you loop through an ArrayList?**
A: Use enhanced for loop: `for (String item : list) { }` or traditional: `for (int i = 0; i < [Link](); i++) { }`
---
## Study Tips
- **Don't memorize**: Understand the concept
- **Practice by building**: Write code, don't just read
- **Google liberally**: It's normal to look things up while coding
- **Read error messages**: They tell you exactly what's wrong
- **Build incrementally**: Make small changes, test frequently
- **Use IDE autocomplete**: Let VS Code/IntelliJ help you
---
**Last Updated:** June 2026
**Scope:** Java fluency for backend development
**Next Step:** Use these notes while building your Job Tracker project in Week 3-4