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 Strings as Objects: The String Pool, == vs equals, StringBuilder and printf

Three Strings all say Java, yet first == third is false. Literals share a box on the string pool, new builds its own, and equals compares letters. Plus String methods that never change the original, StringBuilder in a loop, and printf widths.

Chaand Sheikh

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

What you will learn

  • Explain the string pool and why new String("Java") == "Java" is false
  • Compare String text with equals, not ==
  • Use strip, substring, replace, split and charAt knowing each returns a new String
  • Build text in a loop with StringBuilder and line it up with printf

Before you start

  • Java strings and text blocks
  • Java final and immutable objects

A String isn't a primitive like int; it's an object. That has a surprising effect: here, all three variables hold the text "Java", and first == third is still false.

Same text, same box?

package org.studyeasy.s03l08;

public class Ex01_StringPool {
    public static void main(String[] args) {
        String first = "Java";               // literal: kept on the shared pool shelf
        String second = "Java";              // same text, so it points at the same box
        String third = new String("Java");   // new: always builds its own box

        System.out.println("first == second: " + (first == second));
        System.out.println("first == third:  " + (first == third));
        System.out.println("equals:          " + first.equals(third));
    }
}
first == second: true
first == third:  false
equals:          true
The string pool holds one box with "Java"; first and second both point at it, so first == second is true. third points at its own box built by new, outside the pool, so first == third is false. equals compares the letters, and both boxes hold Java, so equals is true. first second third "Java" "Java" string pool own box (new) == : same box? first, second: true first, third: false equals: same letters? first, third: true
== compares the arrows; equals compares the letters.

Literals go on the string pool, a shared shelf. first and second both say "Java", so Java doesn't make a second box; both point at the same one. new String("Java") always builds a fresh box outside the pool.

== asks only: do the arrows end at the same box? equals asks: are the letters the same? So to compare the text of two Strings, always use equals. A check like if (third == "Java") is false even though the letters match.

Every method hands back a new String

package org.studyeasy.s03l08;

public class Ex02_TextMethods {
    public static void main(String[] args) {
        String raw = "  laptop stand  ";
        String item = raw.strip();                    // a new String without the edge spaces
        System.out.println("[" + item + "]");
        System.out.println(item.substring(0, 6));     // characters 0 to 5
        System.out.println(item.replace(" ", "-"));   // space becomes a dash
        String[] words = item.split(" ");             // cut wherever there is a space
        System.out.println(words.length + " words");
        System.out.println(item.charAt(0));           // the first character
        System.out.println("[" + raw + "]");          // raw never changed
    }
}
[laptop stand]
laptop
laptop-stand
2 words
l
[  laptop stand  ]

strip drops the edge spaces, substring(0, 6) takes characters 0 to 5, replace swaps the space for a dash, split cuts the text into an array of two words, and charAt(0) gives the first character. The last line shows raw unchanged, spaces and all. Strings are immutable (like the Money class): every method reads the String and returns a new value. So raw.strip(); on its own line does nothing useful; the result is thrown away.

One StringBuilder, grown in a loop

package org.studyeasy.s03l08;

public class Ex03_BuildInLoop {
    public static void main(String[] args) {
        String[] items = {"Pen", "Notebook", "Tape"};
        StringBuilder basket = new StringBuilder("Basket:");
        for (String item : items) {
            basket.append(" ");
            basket.append(item);                 // grows the same builder
        }
        String summary = basket.toString();      // a normal String again
        System.out.println(summary);
    }
}
Basket: Pen Notebook Tape

With text = text + " Pen", every pass makes a new String box and throws the old one away. A StringBuilder is one box that grows: each append adds to the same buffer, and toString() hands back a normal String at the end. When you build text in a loop, use one StringBuilder.

Line things up with printf

package org.studyeasy.s03l08;

public class Ex04_FormatText {
    public static void main(String[] args) {
        String item = "Pen";
        int qty = 7;
        // [ ] show where the spaces go.
        System.out.printf("[%s]%n", item);    // as it is
        System.out.printf("[%8s]%n", item);   // 8 wide, right aligned
        System.out.printf("[%-8s]%n", item);  // - = left aligned
        System.out.printf("[%d]%n", qty);     // whole number
        System.out.printf("[%4d]%n", qty);    // 4 wide
        System.out.printf("[%04d]%n", qty);   // 0 = zeros
    }
}
[Pen]
[     Pen]
[Pen     ]
[7]
[   7]
[0007]
double price = 3.5;
System.out.printf("[%.2f]%n", price);   // always 2 places after the dot
System.out.printf("[%8.2f]%n", price);  // 8 wide in total, 2 after the dot
[3.50]
[    3.50]

%s is text, %d a whole number, %f a decimal, and %n ends the line (printf doesn't add one by itself, unlike println). A number sets the width, - left-aligns, a leading 0 pads with zeros, and .2 fixes two decimal places. The type must match: printf("[%d]", 3.5) stops with an error. You don't need to memorise the patterns; just know they exist and look up the one you need.

Recap

IdeaRemember
String poolliterals with the same text share one box
new Stringalways builds its own box
== vs equalssame box vs same letters; compare text with equals
String methodsreturn a new String; the original never changes
StringBuilderone growing box; append, then toString
printf%s, %d, %f, width, -, 0, .2

Keep going in Java · 30 of 79

Previous
Java final and Immutable Objects: Assign Once, Share Safely
Next post
Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
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

  • Same text, same box?
  • Every method hands back a new String
  • One StringBuilder, grown in a loop
  • Line things up with printf
  • 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.