Java: From Zero to Practical
A concise course covering Java fundamentals to intermediate topics, with examples and exercises.
Author: Generated by ChatGPT
Contents
1. Course Overview & Setup
2. Java Basics: Types, Variables, and Operators
3. Control Flow & Methods
4. Object-Oriented Programming (Classes & Objects)
5. Inheritance, Polymorphism & Interfaces
6. Collections Framework
7. Exceptions & Error Handling
8. Java 8+: Lambdas, Streams, and Functional Style
9. Concurrency: Threads & Executors
10. File I/O & Serialization
11. Networking & HTTP (brief)
12. Project: Simple To-Do App (console or file-backed)
Appendix: Cheatsheet & Answers
1. Course Overview & Setup
What you'll learn: Java syntax, OOP design, collections, streams, concurrency, and a small project. Tools:
JDK (11+ recommended), an IDE (IntelliJ IDEA or VS Code with Java extensions), and Maven or Gradle
(optional).
Exercises:
- Install JDK and run `java -version` and `javac -version`. Create and run a 'HelloWorld' program.
2. Java Basics: Types, Variables, and Operators
Java is statically typed. Primitive types: byte, short, int, long, float, double, char, boolean. Reference types:
classes, arrays, interfaces. Use strong typing and understand boxing/unboxing.
// Hello world and variables
public class Hello {
public static void main(String[] args) {
String name = "Ada";
int age = 30;
System.out.println("Hello " + name + ", age " + age);
}
}
Exercises:
- Declare variables of different primitive types and print them.
3. Control Flow & Methods
Conditionals (if/else, switch), loops (for, while, enhanced for). Methods (static vs instance), method
overloading, and basic parameter passing.
// Loops and methods
public static int add(int a, int b) {
return a + b;
}
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Exercises:
- Write a method to compute factorial iteratively and recursively.
4. Object-Oriented Programming (Classes & Objects)
Classes encapsulate state and behavior. Constructors, fields, methods, access modifiers
(private/protected/public), and `this` keyword.
// Simple class
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
Exercises:
- Create a `Book` class with title, author, and methods to display info.
5. Inheritance, Polymorphism & Interfaces
Use `extends` for inheritance, override methods with `@Override`, and use interfaces for contracts.
Understand Liskov Substitution and polymorphic references.
// Inheritance example
public class Animal {
public void speak() { System.out.println("..."); }
}
public class Dog extends Animal {
@Override
public void speak() { System.out.println("Woof"); }
}
Exercises:
- Design an interface `Drawable` and implement it in two classes.
6. Collections Framework
Important interfaces: List, Set, Map. Common implementations: ArrayList, LinkedList, HashSet, HashMap.
Iteration, generic types, and common algorithms.
// Collections example
List<String> names = new ArrayList<>();
names.add("Sam");
names.add("Lee");
for (String n : names) System.out.println(n);
Exercises:
- Given a list of integers, return a map of value -> frequency.
7. Exceptions & Error Handling
Checked vs unchecked exceptions. Use try/catch/finally, throw, and custom exceptions. Prefer specific
catches and always clean up resources (try-with-resources).
// Try-with-resources
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Exercises:
- Create a custom exception and throw it when invalid input is given.
8. Java 8+: Lambdas, Streams, and Functional Style
Lambdas and functional interfaces make code concise. Streams allow map/filter/reduce operations on
collections.
// Stream example
List<Integer> nums = Arrays.asList(1,2,3,4,5);
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
Exercises:
- Use streams to compute average of a list of numbers.
9. Concurrency: Threads & Executors
Create threads with Runnable/Thread, use ExecutorService for thread pools, and understand
synchronization, volatile, and common concurrency pitfalls.
// Executor example
ExecutorService ex = Executors.newFixedThreadPool(2);
ex.submit(() -> System.out.println("Task 1"));
ex.submit(() -> System.out.println("Task 2"));
ex.shutdown();
Exercises:
- Write a program that sums parts of an array in parallel using Executors.
10. File I/O & Serialization
Use java.nio.file for modern file handling. Read/write files, work with Paths, and serialize objects with
JSON libraries (Gson or Jackson) for persistence.
// NIO example
Path p = Paths.get("notes.txt");
List<String> lines = Files.readAllLines(p);
Exercises:
- Read a CSV file and parse records into objects.
11. Networking & HTTP (brief)
Use `HttpURLConnection` or `HttpClient` (Java 11+) to make HTTP requests. Parse JSON responses with
a library.
// Java 11 HttpClient (simplified)
HttpClient client = HttpClient.newHttpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.example.com")).build();
HttpResponse<String> res = client.send(req, BodyHandlers.ofString());
System.out.println(res.body());
Exercises:
- Call a public REST API and print a field from JSON response.
12. Project: Simple To-Do App (Console + File Persistence)
Outline: Create a console app that allows adding, listing, completing, and removing tasks. Persist tasks to
a local JSON or text file using java.nio or a small embedded DB.
// Simplified task model (example)
public class Task {
private String text;
private boolean done;
public Task(String text) { this.text = text; this.done = false; }
public void complete() { this.done = true; }
public String toString() { return (done ? "[x] " : "[ ] ") + text; }
}
Project Steps:
- Create Task class and a TaskManager to hold a List.
- Implement console menu: add, list, complete, delete, save, load.
- Persist tasks to a JSON file using a library (Gson/Jackson) or simple text format.
- (Optional) Create a minimal GUI with JavaFX or a simple REST API with Spring Boot.
Appendix: Java Cheatsheet
Declaration int n = 5; String s = "hi";
Class public class X { private int v; public X(int v){this.v=v;} }
Common Collections List, Set, Map, Queue; use ArrayList, HashMap, HashSet
Useful APIs java.nio.file, java.util.concurrent, java.net.http
Build tools Maven (pom.xml), Gradle (build.gradle)
Answers (selected)
Factorial (recursive) example:
public static long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Stream average example:
double avg = nums.stream().mapToInt(Integer::intValue).average().orElse(0.0);