Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder

A Book class strips ' Dune ' to 'Dune' on the way in and formats itself on the way out. Small programs show the forgotten this (prints null), final on a reference, == vs equals and concat vs append, then a three-book aligned catalogue.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Build an immutable Book with private final fields that cleans input with strip()
  • Spot the forgotten-this bug that leaves a field null
  • Tell what final locks and what concat vs append changes
  • Produce an aligned report with formatted() and a StringBuilder

Before you start

  • Java final and immutable objects
  • Java strings as objects

This lab builds a small library catalogue and practises the last few lessons together: constructors and this, final, and strings as objects. It starts with a messy title, " Dune ", and ends with a neat three-column report.

The Book class

package org.studyeasy.s03l09;

public class Book {
    private final String title;
    private final String author;
    private final int year;

    public Book(String title, String author, int year) {
        this.title = title.strip();
        this.author = author.strip();
        this.year = year;
    }

    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public int getYear() { return year; }

    public String toString() {
        return "%s by %s (%d)".formatted(title, author, year);
    }
}

The fields are private final, so a book never changes after it's built. The constructor cleans the data once, on the way in: strip() trims spaces at both ends. toString formats it on the way out: formatted fills the %s, %s, %d placeholders in order.

" Dune " with 7 characters goes into the constructor, strip() stores "Dune" with 4 characters. When printed, toString fills the pattern and gives "Dune by Frank Herbert (1965)". " Dune "7 characters stored: "Dune"4 characters, final Dune by FrankHerbert (1965) strip() toString() Clean once on the way in, format on the way out.
The constructor cleans; toString formats.
package org.studyeasy.s03l09;

public class Ex01_NewBooks {
    public static void main(String[] args) {
        Book dune = new Book("  Dune ", " Frank Herbert", 1965);
        Book emma = new Book("Emma", "Jane Austen", 1815);
        System.out.println(dune);
        System.out.println(emma);
        System.out.println("Title length: " + dune.getTitle().length());
    }
}
Dune by Frank Herbert (1965)
Emma by Jane Austen (1815)
Title length: 4

println calls toString for you. The title is 4 characters: 7 minus the 3 spaces. Remove .strip() from the constructor and it prints 7.

The forgotten this

package org.studyeasy.s03l09;

public class Ex02_ForgottenThis {
    public static void main(String[] args) {
        BookDraft b = new BookDraft("Dune");
        System.out.println(b.title);
    }
}

class BookDraft {
    String title;

    BookDraft(String title) {
        title = title;
    }
}
null

Inside the constructor, plain title means the parameter, on both sides. So the parameter is copied onto itself and the field is never set: it keeps its default, null. There's no error, which is what makes this bug sneaky. Write this.title = title; and the output becomes Dune (see constructors and this).

final locks the variable, not the object

package org.studyeasy.s03l09;

public class Ex03_FinalShelf {
    public static void main(String[] args) {
        final Shelf shelf = new Shelf();
        shelf.count = 5;
        shelf.count++;
        // shelf = new Shelf();   // compile error: final
        System.out.println("Count: " + shelf.count);
    }
}

class Shelf {
    int count;
}
Count: 6

shelf can only ever point to this one object, but count isn't final, so it goes to 5, then 6. Uncomment shelf = new Shelf(); and the compiler refuses. That's why Book marks its own fields final: so the book itself can't change.

== vs equals, concat vs append

String a = "Emma";
String b = "Emma";
String c = new String("Emma");
System.out.println("a == b: " + (a == b));
System.out.println("a == c: " + (a == c));
System.out.println("a.equals(c): " + a.equals(c));
a == b: true
a == c: false
a.equals(c): true

Two literals share one pooled object; new String makes another. == checks the object, equals the letters.

String title = "Emma";
title.concat("!");

StringBuilder note = new StringBuilder("Emma");
note.append("!");

System.out.println("title: " + title);
System.out.println("note: " + note);
title: Emma
note: Emma!

concat hands back a new String, but nothing stores it, so title is still Emma. append changes the builder itself. Write title = title.concat("!"); to keep the result.

The whole catalogue

package org.studyeasy.s03l09;

public class Lab3_Catalogue {
    public static void main(String[] args) {
        Book[] shelf = {
            new Book("  Dune ", " Frank Herbert", 1965),
            new Book("Emma", "Jane Austen", 1815),
            new Book("Beloved", "Toni Morrison", 1987)
        };

        String row = "%-9s %-14s %4s%n";
        StringBuilder report = new StringBuilder();
        report.append(row.formatted("Title", "Author", "Year"));
        for (Book b : shelf) {
            report.append(row.formatted(b.getTitle(), b.getAuthor(), b.getYear()));
        }
        report.append("Books on shelf: " + shelf.length);
        System.out.println(report);
    }
}
Title     Author         Year
Dune      Frank Herbert  1965
Emma      Jane Austen    1815
Beloved   Toni Morrison  1987
Books on shelf: 3

One pattern serves every row: %-9s pads the title to 9 characters, left-aligned; %-14s pads the author to 14; %4s gives the year 4; %n ends the line. A StringBuilder collects the header, one row per book and the count, and a single println prints it all. Change %-9s to %-4s and the columns stop lining up.

Recap

IdeaIn this lab
Clean on the way intitle.strip() in the constructor
Immutable classprivate final fields, getters, no setters
this.fieldforget it and the field stays null
final referencelocks the variable, not the object
String vs StringBuilderconcat returns new; append changes in place
Formatting"%-9s %-14s %4s%n".formatted(...)

Try it yourself: add a fourth book and a line at the end showing the oldest book on the shelf.

Keep going in Java · 31 of 79

Previous
Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
Next post
Java Inheritance: extends, super and the Order Objects Are Built
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • The Book class
  • The forgotten this
  • final locks the variable, not the object
  • == vs equals, concat vs append
  • The whole catalogue
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.