CIPHERCODE.AI · JAVA INTERMEDIATE

Java builds real programs

OOP depth, streams, files and testing: the jump from scripts to projects.

  • 3 modules
  • Line-by-line code
  • Quizzes + practice

    Module 1

    Inheritance, abstract classes and interfaces

    Reuse code with extends, define contracts with interfaces, and use polymorphism.

    About 90 minutes

    Inheritance lets a child class reuse a parent with extends. An interface is a contract: it lists methods a class promises to implement. Polymorphism means one reference type (the parent or interface) can hold many different objects, and Java calls the right method at runtime.

    ToolUse whenKey rule
    extends"is-a" relationship (Dog is an Animal)A class has only ONE parent
    abstract classShared code plus some methods children must fill inCannot be created with new
    interfaceA capability many unrelated classes shareA class can implement MANY
    Shapes.java
    interface Shape { double area(); }
    
    class Circle implements Shape {
        private double r;
        Circle(double r) { this.r = r; }
        @Override public double area() { return Math.PI * r * r; }
    }
    class Rect implements Shape {
        private double w, h;
        Rect(double w, double h) { this.w = w; this.h = h; }
        @Override public double area() { return w * h; }
    }
    public class Shapes {
        public static void main(String[] args) {
            Shape[] list = { new Circle(1), new Rect(2, 3) };
            for (Shape s : list) System.out.println(s.area());
        }
    }
    Line 1 is the contract. implements Shape forces Circle and Rect to supply area(). @Override makes the compiler check you really match the contract. The array type is Shape, yet each slot holds a different object; the JVM picks the right area() at runtime. That is polymorphism, and adding a Triangle later needs no change to the loop.

    Key takeaways

    • extends = reuse, single parent; implements = contract, many allowed
    • Abstract classes cannot be instantiated
    • @Override lets the compiler catch signature mistakes
    • Polymorphism: parent type reference, child behaviour

    Practice

    Add a Square that implements Shape and add it to the array.

    Square needs one field, the side, and area is side * side.

    Square.java
    class Square implements Shape {
        private double s;
        Square(double s) { this.s = s; }
        @Override public double area() { return s * s; }
    }

    Quick quiz

    Why can an abstract class not be created with new?

    Module 2

    Lambdas and Streams

    Write short functions inline and process collections as pipelines.

    About 75 minutes

    A lambda is an anonymous function written (x) -> x * 2. A stream turns a collection into a pipeline: source, then intermediate steps (filter, map, sorted), then one terminal step (collect, count, forEach). Nothing runs until the terminal step.

    Pipeline.java
    import java.util.*;
    import java.util.stream.*;
    
    public class Pipeline {
        public static void main(String[] args) {
            List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
            List<Integer> out = nums.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .collect(Collectors.toList());
            System.out.println(out);
            System.out.println(nums.stream().mapToInt(n -> n).sum());
        }
    }
    stream() opens the pipeline. filter(n -> n % 2 == 0) keeps evens: 2,4,6. map(n -> n * n) squares each: 4,16,36. collect ends the pipeline into a new list; the original list is unchanged. mapToInt(...).sum() adds all numbers.

    Key takeaways

    • Lambda syntax: (params) -> expression
    • filter keeps, map transforms, collect gathers
    • Lazy: nothing runs without a terminal operation
    • Streams do not modify the source

    Practice

    From a list of names, print those longer than 3 letters in upper case.

    Chain filter(s -> s.length() > 3), map(String::toUpperCase), forEach(System.out::println).

    Names.java
    names.stream()
         .filter(s -> s.length() > 3)
         .map(String::toUpperCase)
         .forEach(System.out::println);

    Quick quiz

    Which is a terminal operation?

    Module 3

    Files and JUnit testing

    Read and write files safely and prove your code works with automated tests.

    About 75 minutes

    Files can fail (missing, locked), so Java forces you to handle IOException. try-with-resources closes the file for you even when an error occurs. A unit test checks one small method automatically; JUnit 5 is the standard tool.

    Notes.java
    import java.nio.file.*;
    import java.util.List;
    import java.io.IOException;
    
    public class Notes {
        public static void main(String[] args) throws IOException {
            Path p = Path.of("notes.txt");
            Files.writeString(p, "learn java\nbuild app\n");
            List<String> lines = Files.readAllLines(p);
            System.out.println(lines.size() + " lines, first: " + lines.get(0));
        }
    }
    Path.of names the file. writeString creates or overwrites it. readAllLines returns each line as a list item. throws IOException passes the possible failure up instead of catching it here.
    CalcTest.java
    import org.junit.jupiter.api.Test;
    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    class CalcTest {
        @Test
        void addsTwoNumbers() {
            assertEquals(5, 2 + 3);
        }
    }
    @Test marks a test method. assertEquals(expected, actual) fails the test when they differ. Run with mvn test. Name tests by behaviour and test one idea each.

    Key takeaways

    • Use Path and Files for modern file I/O
    • Handle or declare IOException
    • try-with-resources auto-closes resources
    • JUnit: @Test + assertEquals, one idea per test

    Practice

    Write a test that checks "java".toUpperCase() equals JAVA.

    Use assertEquals("JAVA", "java".toUpperCase()).

    UpperTest.java
    @Test
    void upper() {
        assertEquals("JAVA", "java".toUpperCase());
    }

    Quick quiz

    What does try-with-resources guarantee?

    EXAM READINESS EXTENSION · INTERMEDIATE

    Core Java topics often missing from short courses

    Use this material alongside inheritance, streams, files and testing. These are high-value topics in college papers, placement tests and Core Java interviews: contracts of common object methods, generics, collection choice, complexity, exceptions, JDBC and language features.

    Definition bank: Intermediate Java definitions

    Learn these concise definitions for theory questions. In written exams, define the term first, then add a short example when asked.

    Inheritance
    An object-oriented feature in which a class extends another class and inherits accessible members.
    Superclass and subclass
    The superclass is the class being extended; the subclass is the class that extends it.
    Polymorphism
    The ability to use a common parent type or interface while different implementations provide different behavior.
    Method overriding
    A subclass provides its own implementation of an inherited instance method with a compatible signature.
    Method overloading
    A class declares multiple methods with the same name but different parameter lists.
    Abstract class
    A class that cannot be instantiated directly and can contain both abstract and implemented methods.
    Interface
    A reference type that defines a contract a class can implement; interfaces can also contain certain default and static methods.
    Generic type
    A class, interface or method parameterized by types, such as List<String>, to improve type safety.
    Wildcard
    The ? symbol in a generic type argument, used when the exact type argument is unknown or bounded.
    Lambda expression
    A concise way to provide an implementation of a functional interface, often written with ->.
    Functional interface
    An interface with one abstract method, suitable as the target type for a lambda expression.
    Stream API
    A pipeline API for processing sequences of data through operations such as filter, map and collect.
    Intermediate and terminal stream operations
    Intermediate operations build a pipeline and are generally lazy; a terminal operation triggers processing and produces a result or side effect.
    List, Set and Map
    List preserves positional order and allows duplicates; Set models unique elements; Map associates keys with values.
    equals() and hashCode()
    equals defines logical equality; hashCode supplies a hash value and must be consistent for objects considered equal.
    Comparable and Comparator
    Comparable defines a type’s natural ordering; Comparator defines an ordering separately, often for sorting in different ways.
    Immutable object
    An object whose observable state cannot be changed after construction.
    Checked exception
    An exception type that Java requires code to catch or declare, except for unchecked exception categories.
    Try-with-resources
    A try statement that automatically closes declared resources implementing AutoCloseable.
    JDBC
    Java Database Connectivity, the standard Java API for connecting to databases and executing SQL.
    PreparedStatement
    A JDBC object for parameterized SQL; it helps separate SQL structure from values and reduces SQL injection risk.
    Transaction
    A group of database operations treated as one unit that can be committed or rolled back.
    Unit test
    A test that checks a small unit of behavior, usually a method or class, in isolation as far as practical.
    JUnit
    A widely used Java testing framework for writing and running automated tests.
    Big-O notation
    A way to describe an upper-bound growth rate for resource use as input size increases, ignoring constant factors.

    1. Generics and type safety

    Generics parameterize types so the compiler can catch incompatible values. Prefer List over a raw List. Generic type arguments cannot be primitive types; use wrappers such as Integer.

    List names = new ArrayList<>();
    names.add("Mira");
    String first = names.get(0);
    // names.add(42); // compile-time error

    Know generic classes, generic methods, bounded type parameters such as <T extends Number>, and wildcards. ? extends T is useful for reading values as T; ? super T is useful when adding T values (PECS: Producer Extends, Consumer Super).

    2. Collection choice and complexity

    List preserves order and permits duplicates; Set models uniqueness; Map associates keys with values. ArrayList is strong for indexed reads, LinkedList supports deque operations, HashSet/HashMap usually offer average constant-time basic operations, and TreeSet/TreeMap keep sorted order.

    StructureTypical useTypical cost
    ArrayListIndexed access, appendget O(1); append amortized O(1); middle insert O(n)
    HashMap / HashSetLookup by key / uniquenessAverage O(1), subject to hashing and implementation
    TreeMap / TreeSetSorted keys / valuesO(log n) basic operations
    ArrayDequeQueue or stack operationsAmortized O(1) at ends

    3. equals() and hashCode()

    When overriding equals, also override hashCode. Equal objects must have equal hash codes; unequal objects may share a hash. Hash-based collections use these methods to find logical matches.

    final class User {
        private final int id;
        User(int id) { this.id = id; }
        @Override public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof User)) return false;
            return id == ((User) o).id;
        }
        @Override public int hashCode() {
            return Integer.hashCode(id);
        }
    }

    For newer Java versions, pattern matching may simplify type checks, but use syntax supported by your exam's target version.

    4. Comparable vs Comparator

    Comparable defines a type's natural ordering with compareTo. Comparator defines an external or alternate ordering. Comparators are useful for sorting by different fields.

    List names = new ArrayList<>(
        List.of("Zoe", "Ana", "Mira"));
    names.sort(Comparator.naturalOrder());
    names.sort(Comparator.comparingInt(String::length));

    Comparison should be consistent and avoid subtraction-based comparators that can overflow. Use Integer.compare(a, b) for integer comparison.

    5. Exceptions, immutability and resources

    Checked exceptions must be caught or declared; unchecked exceptions derive from RuntimeException. Do not swallow exceptions silently. Custom exceptions should communicate a meaningful failure. Immutable objects are easier to reason about and safer to share.

    try (BufferedReader reader = Files.newBufferedReader(path)) {
        String line = reader.readLine();
        System.out.println(line);
    } catch (IOException e) {
        System.err.println("Could not read file: " + e.getMessage());
    }

    Try-with-resources closes AutoCloseable resources. finally is for cleanup that must happen whether or not an exception occurs, though resources are usually better managed with try-with-resources.

    6. JDBC essentials

    JDBC connects Java code to relational databases. Know Connection, PreparedStatement, ResultSet, transactions and SQL exceptions. Use placeholders instead of concatenating untrusted input into SQL.

    String sql = "SELECT name FROM student WHERE id = ?";
    try (Connection c = dataSource.getConnection();
         PreparedStatement ps = c.prepareStatement(sql)) {
        ps.setInt(1, studentId);
        try (ResultSet rs = ps.executeQuery()) {
            if (rs.next()) System.out.println(rs.getString("name"));
        }
    }

    Driver configuration and DataSource setup depend on the environment. For transactions, understand commit, rollback and auto-commit.

    More language and API points to revise

    Exam-style questions with worked answers

    Q1. Why should equals() and hashCode() be overridden together?

    Answer: Hash-based collections first use the hash code to select a bucket and then use equality to identify a matching key. If equal objects have different hash codes, lookups can fail to find logically equal keys.

    Q2. What is printed?
    List values = new ArrayList<>(List.of(1, 2, 3, 4));
    int count = values.stream().filter(n -> n % 2 == 0).count();
    System.out.println(count);

    Answer: 2. The filter keeps 2 and 4; count() is a terminal operation that evaluates the stream.

    Q3. Explain checked and unchecked exceptions.

    Answer: Checked exceptions are checked by the compiler and must be caught or declared, for example IOException. Unchecked exceptions, including NullPointerException and IllegalArgumentException, do not have that compile-time handling requirement.

    Q4. When choose HashMap instead of TreeMap?

    Answer: Choose HashMap when sorted iteration is not needed and average fast key lookup is desired. Choose TreeMap when keys must remain sorted or range/navigation operations are useful.

    Q5. How do you prevent SQL injection in a lookup?

    Answer: Use a PreparedStatement with placeholders and bind values using setter methods. Do not concatenate untrusted input into SQL text.

    Programming practice set

    1. Count word frequencies using a Map, ignoring case and punctuation.
    2. Sort employees by department, then salary descending, then name.
    3. Implement an immutable Money or Student class with validation and correct equality.
    4. Group a list of transactions by category using streams and calculate totals.
    5. Write a method that reads a UTF-8 text file safely and reports useful errors.
    6. Design a repository method using JDBC and a transaction; explain rollback behaviour.

    Next up

    Keep going when you are ready.

    Continue