Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 201 ยท Strings

Strings

Learn how Java strings work, from literals, length and charAt to immutability, equals vs ==, the string pool, intern, compareTo, isEmpty and isBlank.

Text is everywhere in software: names, messages, file paths, JSON, SQL, log lines. In Java, a piece of text is a String, and it's probably the class you will use more than any other. You've already printed strings with IO.println("Hello"); now it's time to understand what they really are.

A String is an object that holds a sequence of characters. It's part of java.lang, so you never need an import, and Java gives it special support: literals in double quotes, the + operator for joining, and a shared pool of reused strings. This lesson covers the fundamentals that every Java developer must know cold, especially two that cause real bugs: strings are immutable, and you must compare them with equals(), not ==.

Creating strings

The usual way to make a string is a string literal: text between double quotes.

Java
String greeting = "Hello, world!";
String empty = "";          // a real string with zero characters
String nothing = null;      // no string at all
char initial = 'H';         // a single char uses single quotes

Note the difference between "" and null. The empty string is a perfectly good object you can call methods on; null means the variable refers to no object, and calling a method on it throws a NullPointerException.

You can also build strings from other values:

Java
String fromNumber = String.valueOf(42);           // "42"
String fromChars = new String(new char[] {'J', 'a', 'v', 'a'});  // "Java"
String copy = new String("text");                 // legal, but almost never needed

new String("text") creates a second, separate object with the same characters. Since strings can't change, there's no reason to copy one, so avoid this form. Special characters such as newlines and quotes inside a literal use escape sequences like \n and \", covered in Text Blocks and Escape Sequences.

Length and individual characters

length() returns the number of characters, and charAt(index) returns the char at a position. Indexes start at 0, so the last character is at length() - 1:

Java length and charAt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that length() is a method with parentheses, while arrays use a length field without them. Mixing the two up is a common compile error for beginners.

Strictly speaking, a String stores UTF-16 code units, and length() counts those. Every common letter, digit and symbol is one unit, but some characters, including most emoji, take two. So "๐Ÿ˜€".length() is 2. Characters and Booleans explains code points and how to count "real" characters.

Joining strings

The + operator joins (concatenates) strings. If either operand is a String, the other one is converted to text automatically, whether it's a number, a boolean, a char, an object or even null:

Java Concatenation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The left-to-right rule comes from Operator Precedence: once the expression on the left is a string, every following + appends. Use parentheses when you want arithmetic first.

+ is perfect for joining a few pieces. Inside a loop that runs thousands of times, though, each += creates a brand-new string, which gets slow. StringBuilder solves that.

Strings are immutable

Once a String object is created, its characters can never change. No method modifies a string in place. Methods like toUpperCase(), replace() and trim() all return a new string and leave the original untouched.

Java Immutability in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call is a classic bug: it looks like it changes name, but the result is discarded. Remember that the variable can be made to point at a different string, but the string object itself never changes.

Immutability isn't a limitation; it's a deliberate design that makes strings:

  • Safe to share. You can pass a string to any method without worrying that it will be altered behind your back.
  • Thread-safe. Many threads can read the same string with no locking.
  • Good keys. A String's hash code never changes, so it can be cached and strings work reliably as keys in a HashMap.
  • Poolable. Identical literals can share one object, as you'll see next.

You can apply the same idea to your own classes; Immutable Classes shows how.

Comparing strings: equals() vs ==

This is the most important rule in this lesson: compare string contents with equals(). The == operator only checks whether two variables refer to the same object, which is a different question (see Comparison and Logical Operators).

Java equals() vs ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All four strings contain java, and equals() says so every time. == gives different answers depending on how the strings were created, which is exactly why you shouldn't use it: code that compares with == often works in a quick test with literals, then fails when the text comes from user input, a file or a database.

Two habits avoid NullPointerException when comparing:

  • Put the literal first: "yes".equals(answer) returns false for a null answer instead of throwing.
  • Use java.util.Objects.equals(x, y) when both sides could be null.

The string pool and intern()

Why did a == b print true? Because the JVM keeps a string pool: a table of unique string objects for literals. When two literals have the same text, they refer to the same pooled object. This saves memory, and it's only safe because strings are immutable.

The compiler also pools constant expressions. "ja" + "va" is computed at compile time, so it's the same object as "java". The same goes for final variables holding literals. But anything computed at run time, including concatenation with a non-final variable, input and method results, produces a new object.

The intern() method returns the pooled version of a string, adding it to the pool if needed:

Java Constant folding and intern()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You'll rarely call intern() yourself. It can save memory when a program holds millions of copies of the same few strings, but equals() is always the right way to compare text. Treat the pool as an optimization you can explain in an interview, not something your logic depends on.

Ordering strings with compareTo()

equals() answers "same or not?". To sort strings you need "which comes first?", and that's compareTo(). a.compareTo(b) returns:

  • a negative number if a comes before b,
  • zero if they're equal,
  • a positive number if a comes after b.

The comparison is lexicographic: Java compares the strings character by character using their UTF-16 values. At the first difference, the result is the difference between those two characters. If one string is a prefix of the other, the shorter one comes first and the result is the difference in lengths.

Java compareTo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three things to remember about compareTo():

  1. Only the sign is meaningful. The exact numbers (like -1 or -7) are an implementation detail; write < 0, == 0 and > 0.
  2. It's case-sensitive. All uppercase letters sort before all lowercase letters, so "Zebra" comes before "apple". Use compareToIgnoreCase() for case-insensitive order.
  3. It's not language-aware. It doesn't know that "รฉ" belongs near "e", or that "item9" should come before "item10" for humans. Comparing and Converting Strings shows how Collator sorts text the way people expect.

Empty and blank strings

Input often arrives empty or full of spaces, so you need to check for both. isEmpty() returns true only when the length is 0. isBlank() (Java 11+) returns true when the string is empty or contains only whitespace, such as spaces, tabs and newlines.

Java isEmpty vs isBlank

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

For validating user input, isBlank() is almost always what you want: a name made only of spaces is no name at all. Both methods are instance methods, so guard against null first, as in the last example, thanks to the short-circuit ||.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? String s = "code"; s.toUpperCase(); IO.println(s);

    Strings are immutable. toUpperCase() returns a new string, but the result is not stored, so s still refers to "code".
  2. 2. Which expression reliably checks whether input contains the text "quit"?

    equals() compares contents. Putting the literal first also makes it safe when input is null. == compares object identity, which depends on how the string was created.
  3. 3. String a = "hi"; String b = new String("hi"); What is a == b?

    new String always creates a separate object, so the references differ. a.equals(b) would be true.
  4. 4. What is the sign of "Apple".compareTo("apple")?

    compareTo is case-sensitive and compares UTF-16 values: 'A' (65) is less than 'a' (97), so the result is negative.
  5. 5. For which string is isBlank() true but isEmpty() false?

    A string of spaces has a length of 2, so it isn't empty, but it contains only whitespace, so it is blank.

Summary

  • A String is an immutable object holding a sequence of UTF-16 characters. "" is an empty string; null is no string at all.
  • length() counts characters; charAt(i) reads one, with indexes from 0 to length() - 1.
  • + concatenates and converts other values to text, working left to right.
  • String methods never change the original; they return new strings, so store the result.
  • Compare contents with equals() or equalsIgnoreCase(), never ==. Write "literal".equals(var) or Objects.equals(a, b) to be null-safe.
  • Literals and compile-time constants share objects in the string pool; intern() returns the pooled copy.
  • compareTo() orders strings lexicographically by character code; check only the sign.
  • isEmpty() checks for length 0; isBlank() also treats whitespace-only strings as blank.

Next: String Methods, a tour of the methods you'll use daily to search, slice, split and transform text.