Part 1 · The core language

6Strings in depth

You have used String since lesson 2 as the type for text, without asking what a string really is. This lesson answers that. A string is an object, and that one fact explains how to ask a string questions, why no string method ever changes a string, why == is the wrong way to compare text, and why a faster tool exists for building long texts.

By the end you will be able to

  • explain the difference between a variable that holds a value and one that holds a reference
  • call methods on strings to measure, search, cut and transform them, and read the exceptions they throw
  • explain why name.toUpperCase(); on its own line does nothing
  • say what == and .equals each compare, and why only one of them is right for text
  • process a string one character at a time, and convert between text and numbers
  • build long texts with StringBuilder and lay out output with printf
  • say what null is and recognise a NullPointerException

A string is an object, and a variable holds a reference

In lesson 2 a variable was a labelled box with a value in it. For int, double, boolean, char and long that picture is right. These are primitive types: the variable holds the value itself.

String is not a primitive type. A piece of text can be any length, so it cannot sit inside a small fixed box. Instead the characters are kept in a separate block of memory called an object, and the variable holds a reference: a value that says where that object is. Picture the reference as an arrow from the variable to the object.

int count = 5; 5 count the variable holds the value String word = "tea"; word a String object t e a the characters live here the variable holds a reference: where to find the object

The picture has two consequences, and the rest of the lesson follows from them.

What a reference is made of inside the JVM is the JVM's business. You cannot do arithmetic with it or follow it by hand, so the arrow is the right way to think about it. Strings are your first objects. Lesson 8 generalises everything in this section to every object, including ones you design yourself. You will meet the proof of the first consequence for strings in section Strings never change, and for another kind of object in section Building long texts.

Asking a string to do something

In lesson 5 you called library methods such as Math.max. Take the call Math.max(3, 8). The name before the dot, Math, is a class, and max is a static method: a method that belongs to the class and takes all its input from the parentheses.

Most String methods are of the other kind. (A few, such as String.valueOf and String.format, which create a string from something else, are static; you will meet both later in this lesson.) An instance method is called on one particular object. You write the object (or a variable that refers to it), a dot, and the method name. The object in front of the dot is the thing the method works on, so it does not appear again in the parentheses.

Static methodInstance method
Written asMath.max(3, 8)word.length()
Before the dota class namean object, or a variable referring to one
What the method works onwhatever is in the parenthesesthe object before the dot, plus whatever is in the parentheses

Two methods are enough to start. length() returns an int: how many characters the string holds. charAt(i) returns a char: the character at position i (the position of a character is also called its index). Positions are counted from 0, so the first character is at position 0.

code/m06-strings/Probe.java
public class Probe {
    public static void main(String[] args) {
        String word = "banana";
        System.out.println(word.length());
        System.out.println(word.charAt(0));
        System.out.println(word.charAt(5));
        System.out.println(word.charAt(word.length() - 1));
        System.out.println("tea".length());
        System.out.println(Math.max(3, 8));
    }
}
Terminal, in code/m06-strings
> javac Probe.java
> java Probe
6
b
a
a
3
8

The string "banana" has six characters at positions 0 to 5. Line 4 prints its length, 6. Lines 5 and 6 print the characters at positions 0 and 5. Line 7 finds the last character without counting by hand: the last position is one less than the length, so word.length() - 1. Line 8 shows that a string literal is an object too, so "tea".length() works without a variable. Line 9 is the lesson 5 static call, for contrast.

Reading StringIndexOutOfBoundsException

Ask for a position that does not exist and the JVM stops the program:

code/m06-strings/OutOfRange.java
public class OutOfRange {
    public static void main(String[] args) {
        String word = "banana";
        System.out.println("The word has " + word.length() + " letters.");
        System.out.println(word.charAt(6));
        System.out.println("Done.");
    }
}
Terminal, in code/m06-strings
> javac OutOfRange.java
> java OutOfRange
The word has 6 letters.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 6 out of bounds for length 6
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
	at java.base/java.lang.String.checkIndex(String.java:5279)
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:58)
	at java.base/java.lang.String.charAt(String.java:1843)
	at OutOfRange.main(OutOfRange.java:5)

The first line of the report names the exception and gives the message: you asked for index 6, and the string has length 6. The valid indexes are 0 to 5, so the message tells you at once that the index is past the end (here by one). The program stopped at line 5, so Done. was never printed.

The lines starting at java.base/... are inside the Java library: that is where the check happened. They are the same kind of lines as in lesson 5's stack trace, and you read them the same way. Skip down to the first at line that names your own file, here OutOfRange.main(OutOfRange.java:5), and that is the statement to fix. The wording of messages like this has varied between Java versions, so a different phrasing elsewhere is not a surprise. This page shows Java 27.

Two compile-time mistakes with instance methods

A method call always needs parentheses, even when there is nothing to put in them. Without them, Java looks for a variable called length inside the string and finds none.

code/m06-strings/broken/NoParens.java
public class NoParens {
    public static void main(String[] args) {
        String word = "banana";
        int n = word.length;
        System.out.println(n);
    }
}
Terminal, in code/m06-strings/broken
> javac NoParens.java
NoParens.java:4: error: cannot find symbol
        int n = word.length;
                    ^
  symbol:   variable length
  location: variable word of type String
1 error

This is the cannot find symbol error from lesson 1. The two extra lines say which name was not found (variable length, not a method) and where the compiler looked (word, of type String). The word variable is the clue that you left the parentheses off.

The opposite slip is to use the static style, with the class name before the dot and the string in the parentheses:

code/m06-strings/broken/StaticStyle.java
public class StaticStyle {
    public static void main(String[] args) {
        String word = "banana";
        System.out.println(String.length(word));
    }
}
Terminal, in code/m06-strings/broken
> javac StaticStyle.java
StaticStyle.java:4: error: method length in class String cannot be applied to given types;
        System.out.println(String.length(word));
                                 ^
  required: no arguments
  found:    String
  reason: actual and formal argument lists differ in length
1 error

The compiler found a length method in String, but it takes no arguments, and you gave it one. length() needs no argument because the string it measures is the object in front of the dot.

Finding and cutting

Most work on text is some form of find a place, then cut there. The tools for it depend entirely on positions, so here are the positions of one word.

p i n e a p p l e 0 1 2 3 4 5 6 7 8 9 no character = length begin = 2: included end = 5: not included substring(2, 5) is "nea"

The word "pineapple" has 9 characters at positions 0 to 8. Position 9, equal to the length, holds no character, but it is a valid number to use when cutting, as you will see.

Finding: indexOf and its relatives

indexOf searches a string and returns the position where the match starts. It accepts a single character ('p') or a string ("apple"). If there is no match it returns -1. That works as a signal because -1 can never be a position.

code/m06-strings/Find.java
public class Find {
    public static void main(String[] args) {
        String fruit = "pineapple";
        System.out.println(fruit.indexOf('p'));
        System.out.println(fruit.indexOf("apple"));
        System.out.println(fruit.indexOf('p', 1));
        System.out.println(fruit.lastIndexOf('p'));
        System.out.println(fruit.indexOf("Apple"));
        System.out.println(fruit.indexOf("z"));
        System.out.println(fruit.contains("nea"));
        System.out.println(fruit.startsWith("pine"));
        System.out.println(fruit.endsWith("pine"));
    }
}
Terminal, in code/m06-strings
> javac Find.java
> java Find
0
4
5
6
-1
-1
true
true
false

Take the output line by line, using the diagram.

Cutting: substring

substring(begin, end) returns a string made of the characters from position begin up to but not including position end. substring(begin) goes from begin to the end of the string.

code/m06-strings/Cut.java
public class Cut {
    public static void main(String[] args) {
        String fruit = "pineapple";
        System.out.println(fruit.substring(4));
        System.out.println(fruit.substring(0, 4));
        System.out.println(fruit.substring(2, 5));
        System.out.println(fruit.substring(4, 9));
        System.out.println("[" + fruit.substring(3, 3) + "]");
        System.out.println("[" + fruit.substring(9) + "]");
    }
}
Terminal, in code/m06-strings
> javac Cut.java
> java Cut
apple
pine
nea
apple
[]
[]

Why leave the end out? Because the two pieces of a cut then fit together with no overlap and no gap: substring(0, 4) is pine, substring(4) is apple, and joined they are the whole word. It also makes the length easy: substring(begin, end) has end - begin characters. substring(2, 5) has 3, as the diagram shows.

The last two lines show the edge cases. When begin equals end you get the empty string "", a string with no characters. A begin equal to the length gives the empty string as well. That is why position 9 was drawn on the diagram.

Predict

Work out what the three println lines print, using the diagram for "pineapple". Write the answers down before you open the answer.

code/m06-strings/predict/Slice.java (lines 3 to 7)
String fruit = "pineapple";
int p = fruit.indexOf("app");
System.out.println(p);
System.out.println(fruit.substring(p, fruit.length() - 1));
System.out.println(fruit.substring(0, fruit.indexOf("e")));
Reveal the answer
Terminal, in code/m06-strings/predict
> javac Slice.java
> java Slice
4
appl
pin

First, indexOf("app") is 4, so p is 4. Then fruit.length() - 1 is 8, so the cut is substring(4, 8): positions 4, 5, 6 and 7, which spell appl. The final e at position 8 is left out because the end is excluded. The last line cuts from 0 up to the first e, which is at position 3, giving pin.

Find, then cut

Put the two together and you can take a piece of text apart. Here an email address is split at the @.

code/m06-strings/EmailParts.java
public class EmailParts {
    public static void main(String[] args) {
        String email = "ada@example.org";
        int at = email.indexOf("@");
        String user = email.substring(0, at);
        String domain = email.substring(at + 1);
        System.out.println("at position " + at);
        System.out.println("user:   " + user);
        System.out.println("domain: " + domain);
    }
}
Terminal, in code/m06-strings
> javac EmailParts.java
> java EmailParts
at position 3
user:   ada
domain: example.org

The user is everything before position 3. The domain starts one past the @, which is why it is at + 1: substring(at) would include the @ itself.

The classic mistake is to cut without checking that the search succeeded. Here the address has a dot where the @ should be.

code/m06-strings/BadSlice.java
public class BadSlice {
    public static void main(String[] args) {
        String email = "ada.example.org";
        int at = email.indexOf("@");
        System.out.println("at is " + at);
        String user = email.substring(0, at);
        System.out.println(user);
    }
}
Terminal, in code/m06-strings
> javac BadSlice.java
> java BadSlice
at is -1
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Range [0, -1) out of bounds for length 15
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
	at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
	at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromToIndex(Preconditions.java:112)
	at java.base/jdk.internal.util.Preconditions.checkFromToIndex(Preconditions.java:349)
	at java.base/java.lang.String.checkBoundsBeginEnd(String.java:5312)
	at java.base/java.lang.String.substring(String.java:3274)
	at BadSlice.main(BadSlice.java:6)

Read the message: the range you asked for runs from 0 to -1, which is not inside a string of length 15. The -1 is a clue. A negative number in an out-of-bounds message very often means an indexOf that found nothing. The fix is to test for it first, with if (at == -1) or if (at < 0), before cutting. Comparing two int values with == is fine, because int is a primitive.

Changed copies and quick questions

Another family of methods gives you the same text in a different form. Each one leaves the original alone and returns a string holding the result. Section Strings never change explains why that matters; for now, notice what each one returns.

code/m06-strings/Copies.java
public class Copies {
    public static void main(String[] args) {
        String raw = "  Blue Moon  ";
        System.out.println("[" + raw + "]");
        System.out.println("[" + raw.strip() + "]");
        System.out.println(raw.toUpperCase());
        System.out.println(raw.toLowerCase());
        System.out.println(raw.replace("Moon", "Sky"));
        System.out.println(raw.replace('o', '0'));
        System.out.println("ha".repeat(3));
        System.out.println(raw.strip().replace(" ", "_").toUpperCase());
    }
}
Terminal, in code/m06-strings
> javac Copies.java
> java Copies
[  Blue Moon  ]
[Blue Moon]
  BLUE MOON  
  blue moon  
  Blue Sky  
  Blue M00n  
hahaha
BLUE_MOON

Line 11 of the program is a method chain: raw.strip().replace(" ", "_").toUpperCase(). Because each method returns a string, you can call another method on that result immediately. Read a method chain from left to right: strip the padding, replace the remaining space, then capitalise.

Two methods ask whether a string has anything in it:

code/m06-strings/Blank.java
public class Blank {
    public static void main(String[] args) {
        System.out.println("".isEmpty());
        System.out.println("   ".isEmpty());
        System.out.println("   ".isBlank());
        System.out.println(" x ".isBlank());
        System.out.println("   ".strip().isEmpty());
    }
}
Terminal, in code/m06-strings
> javac Blank.java
> java Blank
true
false
true
false
true

isEmpty() is true only for the string with zero characters. isBlank() is true for the empty string and also for a string made only of whitespace. A string of three spaces is not empty but is blank, which is why line 4 prints false and line 5 prints true. The last line shows the connection: strip a blank string and what remains is empty.

Strings never change

Look at the methods above: each returns a result, and none changes the string it was called on. That is deliberate. A string is immutable, meaning that once the object exists its characters can never change. There is no method that edits a string in place. A method that appears to change one leaves it alone and gives back a string holding the result.

This is the cause of one of the commonest beginner bugs:

code/m06-strings/Discard.java
public class Discard {
    public static void main(String[] args) {
        String name = "ada";
        name.toUpperCase();
        System.out.println(name);

        String shouted = name.toUpperCase();
        System.out.println(shouted);
        System.out.println(name);

        name = name.toUpperCase();
        System.out.println(name);
    }
}
Terminal, in code/m06-strings
> javac Discard.java
> java Discard
ada
ADA
ada
ADA

Line 4 calls toUpperCase(), which gives back a string holding "ADA". Nothing receives it, so it is thrown away. The compiler does not complain, because calling a method and ignoring its result is legal. The next line prints ada, unchanged. Lines 7 to 9 do it properly: the result goes into a new variable shouted, and name is still ada afterwards. Line 11 shows the usual cure when you want the variable itself to end up upper-case: assign the result back.

Line 11 deserves care, because it looks as if it changes name. It does not. It makes name refer to a different object:

BEFORE AFTER name = name.toUpperCase(); name "ada" name "ADA" new object "ada" old object: unchanged name no longer leads to it

The old object was not edited. The variable simply stopped leading to it. Whether that old object is cleared from memory depends on whether anything else still refers to it; the JVM makes that decision, and you do not do it by hand. Reassigning a variable and changing an object are different things, and with strings only the first is possible.

Which object comes back is up to Java. When the result differs from the original, as with "ADA" and "ada", it is a different object. When nothing needs changing, Java is allowed to hand back the original object itself, and these methods do so:

code/m06-strings/SameObject.java
public class SameObject {
    public static void main(String[] args) {
        String upper = "ABC";
        String lower = "abc";
        System.out.println(lower.toUpperCase() == upper);
        System.out.println(upper.toUpperCase() == upper);
        System.out.println(lower.strip() == lower);
        System.out.println(lower.replace("z", "y") == lower);
    }
}
Terminal, in code/m06-strings
> javac SameObject.java
> java SameObject
false
true
true
true

The first comparison is false: "abc".toUpperCase() is a different object from "ABC". The other three are true: "ABC" is already upper case, strip had nothing to strip, and replace found no z, so each returned the very object it was called on. Do not rely on this either way. It means that you cannot tell from == whether a method gave you a copy, which is one more reason the next section matters.

The operator += follows the same rule. s += "x" means s = s + "x": join to make a new string, then make s refer to it.

Immutability is a design choice with a good reason. Many variables can refer to the same string, as in String b = a;. If a string could be edited through one name, every other name would see the change and be surprised. Because a string cannot change, sharing one is safe.

Predict

Two variables refer to the same string, and then one of them is reassigned. What do the two println calls print?

code/m06-strings/predict/Teapot.java (lines 3 to 7)
String a = "tea";
String b = a;
a = a + "pot";
System.out.println(a);
System.out.println(b);
Reveal the answer
Terminal, in code/m06-strings/predict
> javac Teapot.java
> java Teapot
teapot
tea

It prints teapot and then tea. After line 4, a and b are two arrows to one object holding tea. Line 5 joins a and "pot" into a new object and makes a point at it. It does nothing at all to b, which still points at the original tea. If strings were mutable the answer could have been teapot twice.

Same object or same characters?

Since lesson 3 you have followed a bare rule: compare strings with .equals(...), never with ==. Now there is enough to explain it.

For primitives, == compares the values. For references it compares the references. It asks one question: are these two variables leading to the same object? It never looks at the characters. The method equals asks a different question: do these two strings hold the same characters?

Make a prediction for this program before you look at the answer.

Predict

What do the four println lines print?

code/m06-strings/Identity.java (lines 3 to 12)
String first = "tea";
String second = "tea";
String part = "te";
String built = part + "a";
String alias = first;

System.out.println(first == second);
System.out.println(first == built);
System.out.println(first.equals(built));
System.out.println(first == alias);
Reveal the answer
Terminal, in code/m06-strings
> javac Identity.java
> java Identity
true
false
true
true

The output is true, false, true, true. The second line is the surprise: first and built hold exactly the same characters, tea, and first.equals(built) says so on the third line, yet first == built is false. They are two different objects with equal contents.

Here is what happened, drawn out.

first second built "tea" "tea" one object, shared: first == second is true a second object: first == built is false first.equals(built) is true

Why are first and second the same object? Because identical string literals in a program are shared. The compiler and the JVM keep one object for each distinct literal text, and every place that writes "tea" gets an arrow to it. The text of built never appears as a literal. It is made while the program runs, by joining two pieces, and joining creates a new object.

The last line, alias, is the first consequence from the first section: copying a reference copies the arrow, so first == alias is true, and there was never a second object.

A join the compiler can do early

There is one case where joining does not create a new object while the program runs. If every piece of the join is a literal or a final variable that was given a literal (lesson 2), the compiler can work out the whole result while compiling, and the joined text is shared like any other literal:

code/m06-strings/ConstantJoin.java
public class ConstantJoin {
    public static void main(String[] args) {
        String first = "tea";
        final String part = "te";
        String built = part + "a";
        System.out.println(first == built);
    }
}
Terminal, in code/m06-strings
> javac ConstantJoin.java
> java ConstantJoin
true

Here part is final, so the comparison is true. In Identity, where part was an ordinary variable that could in principle change, it was false. Nobody should write programs that depend on this difference. It is one more reason to leave == alone for text, and exercise 5 asks you to explain it.

Why this bug is dangerous

Comparing strings with == compiles without a warning, and it sometimes gives the right answer. Suppose you test if (answer == "yes") by writing both sides as literals, or by passing a literal into your method. Both are the same shared object, so the test passes, and you move on. Then the program is used with real text: text that was typed by a person, read from a file, cut out with substring or built with a StringBuilder. All of that is created while the program runs, so each piece is usually a new object, and == is false even when the characters are identical.

A bug that appears only with real data, after tests passed, is the worst kind. The rule is simple. Compare the contents of strings with .equals. To test that two strings differ, write !name.equals("Ada"). In your own programs, the everyday use of == on a reference is the test for null, covered at the end of this lesson. Asking the very same object? is occasionally what you want, as in the SameObject and Identity programs, but not when you mean the same text.

Ignoring case, and ordering

Two more comparison methods are worth knowing. equalsIgnoreCase is equals that treats upper-case and lower-case letters as the same. And compareTo says which of two strings comes first in alphabetical order. You cannot use < or > on strings:

code/m06-strings/broken/LessThan.java
public class LessThan {
    public static void main(String[] args) {
        String a = "apple";
        String b = "cherry";
        if (a < b) {
            System.out.println("apple comes first");
        }
    }
}
Terminal, in code/m06-strings/broken
> javac LessThan.java
LessThan.java:5: error: bad operand types for binary operator '<'
        if (a < b) {
              ^
  first type:  String
  second type: String
1 error

The operators < and > are for numbers. Their absence for objects is the compiler telling you that less than has no obvious meaning for text, so you must say what you mean. a.compareTo(b) is the way to say it. It returns an int:

code/m06-strings/Ordering.java
public class Ordering {
    public static void main(String[] args) {
        System.out.println("apple".compareTo("cherry"));
        System.out.println("cherry".compareTo("apple"));
        System.out.println("apple".compareTo("apple"));
        System.out.println("abc".compareTo("abcde"));
        System.out.println("Zebra".compareTo("apple"));
        System.out.println("Zebra".compareToIgnoreCase("apple"));
        System.out.println("Tea".equalsIgnoreCase("tEA"));
    }
}
Terminal, in code/m06-strings
> javac Ordering.java
> java Ordering
-2
2
0
-2
-7
25
true

Rely on the sign, not the size. The number is the difference between the numeric codes of the first pair of characters that differ (lesson 2: a char is a number). 'a' minus 'c' gives -2 on the first line, and the second line is the same pair the other way round. If one string is the start of the other, as with abc and abcde, the number is the difference in lengths, so the shorter string comes first.

Because it compares codes, compareTo puts the capital letters A to Z before all the lower-case letters a to z. "Zebra".compareTo("apple") is -7, negative, because 'Z' is 90 and 'a' is 97. For dictionary order, use compareToIgnoreCase, which gives a positive 25 here. The final line shows equalsIgnoreCase declaring Tea and tEA equal. To test whether a comes before b, write a.compareTo(b) < 0.

Characters

A char and a String are different types, even when a string holds one character. A char is a primitive: a single character, written in single quotes ('a'), stored as a number, compared with ==. A String is an object, written in double quotes ("a"), and has methods. Mixing them up produces compile-time errors:

code/m06-strings/broken/WrongQuotes.java
public class WrongQuotes {
    public static void main(String[] args) {
        String word = "banana";
        char first = word.substring(0, 1);
        String last = word.charAt(5);
        System.out.println(first + last);
    }
}
Terminal, in code/m06-strings/broken
> javac WrongQuotes.java
WrongQuotes.java:4: error: incompatible types: String cannot be converted to char
        char first = word.substring(0, 1);
                                   ^
WrongQuotes.java:5: error: incompatible types: char cannot be converted to String
        String last = word.charAt(5);
                                 ^
2 errors

Incompatible types: X cannot be converted to Y means that you offered a value of type X where type Y was required. The first error is substring, which always returns a String, even for a one-character cut, assigned to a char. The second is charAt, which returns a char, assigned to a String. Match the variable's type to what the method returns. The same mismatch shows up in comparisons:

code/m06-strings/broken/CharCompare.java
public class CharCompare {
    public static void main(String[] args) {
        String word = "banana";
        if (word.charAt(0) == "b") {
            System.out.println("starts with b");
        }
    }
}
Terminal, in code/m06-strings/broken
> javac CharCompare.java
CharCompare.java:4: error: bad operand types for binary operator '=='
        if (word.charAt(0) == "b") {
                           ^
  first type:  char
  second type: String
1 error

The fix is word.charAt(0) == 'b', a char against a char. A char is also not an object, so it has no methods at all:

code/m06-strings/broken/CharMethod.java
public class CharMethod {
    public static void main(String[] args) {
        char letter = 'a';
        System.out.println(letter.length());
    }
}
Terminal, in code/m06-strings/broken
> javac CharMethod.java
CharMethod.java:4: error: char cannot be dereferenced
        System.out.println(letter.length());
                                 ^
1 error

Dereferenced means followed an arrow. The message says that a dot was used on something that is not a reference, so there is nothing to follow.

Looping over a string

length() and charAt are all you need to visit every character. The loop counter runs over the positions, from 0 up to but not including the length.

code/m06-strings/CharLoop.java
public class CharLoop {
    public static void main(String[] args) {
        String text = "Room 101, floor 3!";
        int letters = 0;
        int digits = 0;
        int spaces = 0;
        int others = 0;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (Character.isLetter(c)) {
                letters++;
            } else if (Character.isDigit(c)) {
                digits++;
            } else if (Character.isWhitespace(c)) {
                spaces++;
            } else {
                others++;
            }
        }
        System.out.println("letters: " + letters);
        System.out.println("digits:  " + digits);
        System.out.println("spaces:  " + spaces);
        System.out.println("others:  " + others);
    }
}
Terminal, in code/m06-strings
> javac CharLoop.java
> java CharLoop
letters: 9
digits:  4
spaces:  3
others:  2

The decisions come from the Character class, which has static methods such as these (Character.isLetter(c) is called like Math.max), each taking a char:

MethodReturnsMeaning
Character.isDigit(c)booleanis c a digit, such as 0 to 9?
Character.isLetter(c)booleanis c a letter, such as a or Q?
Character.isUpperCase(c), isLowerCase(c)booleanis c a capital, or a small, letter?
Character.isWhitespace(c)booleanis c a space, tab or line break?
Character.toUpperCase(c), toLowerCase(c)charthe capital, or small, form of c

In the run above, Room 101, floor 3! has 18 characters: 9 letters, 4 digits, 3 spaces, and the comma and exclamation mark as the 2 others. The four counts add up to 18, which is a good check that every character landed in exactly one branch.

Character.toUpperCase returns a char, which can be joined onto a string. This loop capitalises the first letter of each word by remembering whether the previous character was a space:

code/m06-strings/Capitals.java
public class Capitals {
    public static void main(String[] args) {
        String title = "the old man and the sea";
        String result = "";
        boolean startOfWord = true;
        for (int i = 0; i < title.length(); i++) {
            char c = title.charAt(i);
            if (startOfWord) {
                result += Character.toUpperCase(c);
            } else {
                result += c;
            }
            startOfWord = (c == ' ');
        }
        System.out.println(result);
        System.out.println(Character.isUpperCase(result.charAt(0)));
        System.out.println(Character.isUpperCase(result.charAt(1)));
    }
}
Terminal, in code/m06-strings
> javac Capitals.java
> java Capitals
The Old Man And The Sea
true
false

The flag startOfWord is true for the first character, and afterwards it is true only straight after a space. result += c joins a char onto a String, which works because one operand is a string. The last two lines confirm that the first character is capital and the second is not.

Arithmetic on letters

Lesson 2 showed that a char is a number, so letters can be added to and subtracted from. Subtracting 'a' from a lower-case letter gives its distance from a: 0 for a, 1 for b, and so on. Adding that distance back to 'a' after the cast (char) turns the number into a letter again.

code/m06-strings/LetterMath.java
public class LetterMath {
    public static void main(String[] args) {
        char c = 'd';
        int position = c - 'a' + 1;
        char next = (char) (c + 1);
        System.out.println(c + " is letter number " + position);
        System.out.println("the next letter is " + next);

        char x = 'x';
        char shifted = (char) ('a' + (x - 'a' + 3) % 26);
        System.out.println(x + " moved on by 3 is " + shifted);
    }
}
Terminal, in code/m06-strings
> javac LetterMath.java
> java LetterMath
d is letter number 4
the next letter is e
x moved on by 3 is a

For 'd', c - 'a' is 3, so adding 1 for a human-friendly numbering gives 4. Moving 'x' on by 3 would run off the end of the alphabet, so the distance is taken modulo 26: 'x' - 'a' is 23, plus 3 is 26, and 26 % 26 is 0, which is 'a' again. The remainder operator % from lesson 2 is what makes the alphabet wrap round.

There is one trap in all this, and it comes from the same fact. Because a char is a number, two characters added together make a number, not text.

Predict

Which of these lines print a number, and which print text?

code/m06-strings/predict/CharAdd.java (lines 3 to 6)
System.out.println('a' + 'b');
System.out.println("" + 'a' + 'b');
System.out.println('a' + 1);
System.out.println((char) ('a' + 1));
Reveal the answer
Terminal, in code/m06-strings/predict
> javac CharAdd.java
> java CharAdd
195
ab
98
b

Line 3 prints 195: 'a' is 97 and 'b' is 98, and + on two numbers adds them. Line 4 starts with the string "", so + joins from then on, and the output is ab. Line 5 is 'a' + 1, the number 98. Line 6 casts that number back to a char, which prints as b. To turn characters into text, make sure a string is involved before the first +.

Text to numbers and back

The text "42" and the number 42 are different values. The first is an object holding two characters, 4 and 2, and you cannot do arithmetic with it. To get the number you parse the text: read it and work out what number it describes. Two static methods do this, both in the style of Math.max:

Going the other way, String.valueOf(number) returns the digits as a string, and so does a shorthand built on the joining of lesson 2: joining the number to the empty string "", as in "" + n.

code/m06-strings/Parse.java
public class Parse {
    public static void main(String[] args) {
        String text = "42";
        int n = Integer.parseInt(text);
        System.out.println(n + 1);
        System.out.println(text + 1);

        double price = Double.parseDouble("3.75");
        System.out.println(price * 2);

        String fromNumber = String.valueOf(n);
        String joined = "" + n;
        System.out.println(fromNumber.length());
        System.out.println(joined + joined);
    }
}
Terminal, in code/m06-strings
> javac Parse.java
> java Parse
43
421
7.5
2
4242

Line 5 adds 1 to the number, so it prints 43. Line 6 joins 1 to the text, so it prints 421. The same + does two different jobs depending on the types around it. The number 42 has two digits, so its text has length 2, and doubling the text "42" by joining it to itself gives 4242, not 84.

Where does text that needs parsing come from? In lesson 7 your program will receive words typed after the class name on the command line (the line you type in the terminal), and every one of them arrives as a string. parseInt and parseDouble are what make those words usable as numbers.

NumberFormatException

If the text does not describe a number, parsing fails at run time:

code/m06-strings/BadNumber.java
public class BadNumber {
    public static void main(String[] args) {
        String answer = "forty";
        System.out.println("Converting " + answer + "...");
        int n = Integer.parseInt(answer);
        System.out.println(n + 2);
    }
}
Terminal, in code/m06-strings
> javac BadNumber.java
> java BadNumber
Converting forty...
Exception in thread "main" java.lang.NumberFormatException: For input string: "forty"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:529)
	at java.base/java.lang.Integer.parseInt(Integer.java:626)
	at BadNumber.main(BadNumber.java:5)

The message For input string: "forty" repeats the text it could not parse, inside quotes. This is more useful than it looks, because the quotes show you the exact text, including any spaces at its ends. The program above is stopped by the exception at line 5, so line 6 never runs.

code/m06-strings/BadSpace.java
public class BadSpace {
    public static void main(String[] args) {
        String typed = " 42";
        System.out.println(Integer.parseInt(typed.strip()));
        System.out.println(Integer.parseInt(typed));
    }
}
Terminal, in code/m06-strings
> javac BadSpace.java
> java BadSpace
42
Exception in thread "main" java.lang.NumberFormatException: For input string: " 42"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:529)
	at java.base/java.lang.Integer.parseInt(Integer.java:626)
	at BadSpace.main(BadSpace.java:5)

" 42" looks like a number, but the leading space makes it fail. Look closely at the message: there is a space just after the opening quote. Integer.parseInt does not strip whitespace for you. (Double.parseDouble is more forgiving about spaces, so do not assume the two behave alike.) Calling strip() first, as line 4 does, fixes it, and it is the first thing to try whenever parseInt rejects text that looks fine.

code/m06-strings/BadDecimal.java
public class BadDecimal {
    public static void main(String[] args) {
        System.out.println(Double.parseDouble("3.5"));
        System.out.println(Integer.parseInt("3.5"));
    }
}
Terminal, in code/m06-strings
> javac BadDecimal.java
> java BadDecimal
3.5
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.5"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:529)
	at java.base/java.lang.Integer.parseInt(Integer.java:626)
	at BadDecimal.main(BadDecimal.java:4)

Integer.parseInt accepts whole-number text only. The text "3.5" is a perfectly good double, and Double.parseDouble reads it on the first line, but it is not an int, so the second line fails.

Both Integer and Double are ready-made classes from the standard library, like Math. Lesson 7 explains what they are for beyond parsing.

Building long texts: StringBuilder

Lesson 4 built text with += in a loop. Now you know what that does. Each += creates a brand new string and makes the variable refer to it. The old one is abandoned. You can watch this by comparing the reference before and after each pass:

code/m06-strings/Waste.java
public class Waste {
    public static void main(String[] args) {
        String text = "";
        for (int pass = 1; pass <= 3; pass++) {
            String before = text;
            text += "ab";
            System.out.println(text + "  same object as before? " + (text == before));
        }
    }
}
Terminal, in code/m06-strings
> javac Waste.java
> java Waste
ab  same object as before? false
abab  same object as before? false
ababab  same object as before? false

(The == here is deliberate: the question really is same object?) Every pass leaves behind an object and creates a longer one. Building a 1,000-character text one character at a time makes about 1,000 strings, each copying everything before it. For a short text nobody notices; for a large one the cost grows quickly.

The fix is a different kind of object that can change. A StringBuilder holds a sequence of characters that you can add to, insert into and reverse in place. You create one with new:

StringBuilder sb = new StringBuilder();

The word new asks Java to create a fresh object of the named kind in memory and hand back a reference to it, which the variable then holds. You have not needed new for strings because a string literal already is an object. Lesson 8 explains new fully and shows how to define your own kinds of object.

code/m06-strings/Builder.java
public class Builder {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("Tea");
        sb.append(' ');
        sb.append(2);
        sb.append(" cups");
        System.out.println(sb.toString());
        System.out.println(sb.length());

        sb.insert(0, ">> ");
        System.out.println(sb);

        sb.reverse();
        System.out.println(sb);

        sb.reverse().append("!").append("?");
        String result = sb.toString();
        System.out.println(result);
    }
}
Terminal, in code/m06-strings
> javac Builder.java
> java Builder
Tea 2 cups
10
>> Tea 2 cups
spuc 2 aeT >>
>> Tea 2 cups!?
MethodWhat it does
append(x)adds x to the end. x can be a string, a char, a number or a boolean; numbers are added as their digits.
insert(position, x)adds x at the given position, moving the rest along.
reverse()reverses the characters in place.
length()the number of characters, as for a string.
toString()returns the contents as an ordinary (immutable) String.

Notice what is missing from the program: no line says sb = sb.append(...). The calls change the builder itself, and that is the difference from strings. Line 8 prints sb.toString() and line 9 prints sb.length(). Lines 12 and 15 pass the builder itself to println, which prints its characters. Line 19 prints result, the string made by toString() on line 18. append, insert and reverse each also return the builder they were called on, so calls can be chained, as on line 17 of the program. (length returns an int and toString a String, so they end a chain.) A common shape is to build in a builder and call toString() once at the end, to return an ordinary string.

It is worth confirming that the difference in speed is real and not a story:

code/m06-strings/Stopwatch.java
public class Stopwatch {
    public static void main(String[] args) {
        int n = 100000;

        long start = System.currentTimeMillis();
        String slow = "";
        for (int i = 0; i < n; i++) {
            slow += "x";
        }
        long middle = System.currentTimeMillis();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append("x");
        }
        String fast = sb.toString();
        long end = System.currentTimeMillis();

        System.out.println("same result: " + slow.equals(fast));
        System.out.println("+= loop took " + (middle - start) + " ms");
        System.out.println("builder took " + (end - middle) + " ms");
    }
}
Terminal, in code/m06-strings
> javac Stopwatch.java
> java Stopwatch
same result: true
+= loop took 734 ms
builder took 3 ms

System.currentTimeMillis() is a static method that returns the current time in milliseconds as a long, so subtracting two readings gives the time taken. Both loops produce the same 100,000-character text, as the first line shows. The times on your machine will differ from the ones printed on this page, and from run to run, but the += loop takes far longer than the builder.

One builder, two names

A builder is an object like any other, so everything from the first section applies. Copying a builder variable copies the arrow.

Predict

What do these three println lines print? The last one asks whether a and b are the same object. (The line numbers shown are those of the file.)

code/m06-strings/predict/Alias.java (lines 3 to 8)
StringBuilder a = new StringBuilder("tea");
StringBuilder b = a;
b.append("pot");
System.out.println(a);
System.out.println(b);
System.out.println(a == b);
Reveal the answer
Terminal, in code/m06-strings/predict
> javac Alias.java
> java Alias
teapot
teapot
true

Both of the first two lines print teapot, and the comparison is true. Line 4 of the file copied the arrow, so a and b lead to one builder, and appending through b changes the one object that both names see. Compare section Strings never change, where b also started as a copy of a but a was then given a joined string, and the output was teapot and tea. A string cannot be changed through a second name; a builder can. This is the other half of the proof that variables hold references.

Here is the same program continued, with two more comparisons. Line numbers below are those of this file, Aliasing.java.

code/m06-strings/Aliasing.java
public class Aliasing {
    public static void main(String[] args) {
        StringBuilder a = new StringBuilder("tea");
        StringBuilder b = a;
        b.append("pot");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == b);

        StringBuilder c = new StringBuilder("teapot");
        System.out.println(a.equals(c));
        System.out.println(a.toString().equals(c.toString()));
    }
}
Terminal, in code/m06-strings
> javac Aliasing.java
> java Aliasing
teapot
teapot
true
false
true

The builder c holds the same characters as a, yet a.equals(c) on line 11 is false: for a StringBuilder, equals asks the same question as ==, whether the two are the same object. Convert both with toString() and compare those, as line 12 does, to compare contents.

StringStringBuilder
Can its characters change?no: immutableyes: mutable
A method that changes itleaves the original untouched and returns a string holding the resultappend, insert and reverse change the object itself
Best forfixed text that is shared and comparedtext being assembled in many steps

Formatting output

Joining pieces with + gets awkward when you want numbers rounded, or columns that line up. String.format and System.out.printf take a format string, which is ordinary text with format specifiers that start with %, followed by the values to fill them in. String.format returns the result as a string. printf prints it, and, unlike println, does not add a line break by itself.

code/m06-strings/Formats.java
public class Formats {
    public static void main(String[] args) {
        int cups = 3;
        String drink = "tea";
        double price = 2.5;

        System.out.printf("%d cups of %s%n", cups, drink);
        System.out.printf("Price: %.2f%n", price);
        String line = String.format("%s costs %.2f", drink, price);
        System.out.println(line);

        System.out.printf("[%5d]%n", 42);
        System.out.printf("[%-5d]%n", 42);
        System.out.printf("[%3d]%n", 12345);
        System.out.printf("[%10s]%n", drink);
        System.out.printf("[%-10s]%n", drink);
        System.out.printf("[%8.3f]%n", price);
        System.out.printf("%.2f%n", 3.14159);
        System.out.printf("%d%% done%n", 50);
    }
}
Terminal, in code/m06-strings
> javac Formats.java
> java Formats
3 cups of tea
Price: 2.50
tea costs 2.50
[   42]
[42   ]
[12345]
[       tea]
[tea       ]
[   2.500]
3.14
50% done
SpecifierFills inExample from the program
%da whole number, such as an int or a long3 cups
%sany value, as texttea
%.2fa decimal number with 2 places after the point, rounded2.50, and 3.14159 became 3.14
%5da number in at least 5 columns, right-aligned[ 42]
%-5dthe same, left-aligned[42 ]
%3d with 12345a value wider than the width is not cut[12345]
%10s, %-10stext padded to 10 columns, right- or left-aligned[ tea], [tea ]
%8.3fwidth and decimals together[ 2.500]
%na line breakends the lines printed by the printf calls above
%%a literal percent sign50% done

The values after the format string fill the specifiers from left to right, in order. A number after % is a minimum width: if the value is shorter it is padded with spaces, and if it is longer it is not cut. A minus sign puts the padding on the right instead of the left. Use %n rather than \n for the line break in a format string; it produces whatever line break the current system uses.

Widths are what make columns line up:

code/m06-strings/Table.java
public class Table {
    public static void main(String[] args) {
        System.out.printf("%-10s%5s%10s%n", "Item", "Qty", "Price");
        System.out.printf("%-10s%5d%10.2f%n", "Tea", 2, 3.5);
        System.out.printf("%-10s%5d%10.2f%n", "Biscuits", 12, 0.35);
        System.out.printf("%-10s%5d%10.2f%n", "Honey", 1, 12.0);
    }
}
Terminal, in code/m06-strings
> javac Table.java
> java Table
Item        Qty     Price
Tea           2      3.50
Biscuits     12      0.35
Honey         1     12.00

The item names are left-aligned in 10 columns, the quantities right-aligned in 5, and the prices right-aligned in 10 with two decimals, so the digits and decimal points line up whatever the values are.

When the format and the values disagree

The compiler does not check a format string against its values. Mismatches are run-time errors. A specifier of the wrong type:

code/m06-strings/BadFormatType.java
public class BadFormatType {
    public static void main(String[] args) {
        double price = 2.5;
        System.out.printf("Price: %d%n", price);
    }
}
Terminal, in code/m06-strings
> javac BadFormatType.java
> java BadFormatType
Price: Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.Double
	at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4662)
	at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:3200)
	at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:3155)
	at java.base/java.util.Formatter.format(Formatter.java:2761)
	at java.base/java.io.PrintStream.format(PrintStream.java:1163)
	at java.base/java.io.PrintStream.printf(PrintStream.java:1061)
	at BadFormatType.main(BadFormatType.java:4)

d != java.lang.Double reads %d cannot be used with a Double: the d specifier wants a whole number, and price is a double. The fix is %.2f. (The message says java.lang.Double rather than double because it names the library class that goes with double; lesson 7 explains it.) Notice that Price: was printed before the failure, because the text before the specifier had already been sent.

And too few values:

code/m06-strings/BadFormatCount.java
public class BadFormatCount {
    public static void main(String[] args) {
        System.out.printf("%s has %d legs%n", "table");
    }
}
Terminal, in code/m06-strings
> javac BadFormatCount.java
> java BadFormatCount
table has Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%d'
	at java.base/java.util.Formatter.format(Formatter.java:2760)
	at java.base/java.io.PrintStream.format(PrintStream.java:1163)
	at java.base/java.io.PrintStream.printf(PrintStream.java:1061)
	at BadFormatCount.main(BadFormatCount.java:3)

The message names the specifier that had nothing left to fill it: the second one, %d. You gave printf one value, and two specifiers that each need one. (%n needs none.)

printf accepts any number of values after the format string. A method that does so can be written by you; lesson 7 shows how.

Text blocks

You may see strings written between triple quotes. Since Java 15, a text block is a string literal that can run over several lines, with no \n and no escaped quotes. It begins with """ and a line break, and the text starts on the next line.

code/m06-strings/TextBlock.java
public class TextBlock {
    public static void main(String[] args) {
        String poem = """
            Roses are red,
              Violets are blue.
            """;
        System.out.print(poem);
        System.out.println(poem.length());
    }
}
Terminal, in code/m06-strings
> javac TextBlock.java
> java TextBlock
Roses are red,
  Violets are blue.
35

The compiler removes the indentation that every line shares, which is why Roses starts at the left edge while Violets keeps its two extra spaces. The closing """ sits on its own line, so the text ends with a line break; the length of 35 is 15 characters for the first line and 20 for the second, each including its line break. You do not need text blocks in this course, but you now know what they are.

null: a reference to nothing

A reference variable holds an arrow, but an arrow can also point nowhere. The value null is a reference that leads to no object. You can assign it to a String variable like this: String nickname = null;

It is not the same as the empty string. "" is an object that happens to hold no characters, and it answers length() with 0. null is the absence of any object, so there is nothing that could answer.

code/m06-strings/NullDemo.java
public class NullDemo {
    public static void main(String[] args) {
        String nickname = null;
        System.out.println(nickname);
        System.out.println("Nickname: " + nickname);
        System.out.println(nickname == null);
        System.out.println("Ada".equals(nickname));

        String empty = "";
        System.out.println(empty.length());

        System.out.println(nickname.length());
        System.out.println("Done.");
    }
}
Terminal, in code/m06-strings
> javac NullDemo.java
> java NullDemo
null
Nickname: null
true
false
0
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
	at NullDemo.main(NullDemo.java:12)

Working down the output:

Since Java 15 the message describes the failed call: Cannot invoke "String.length()" because "<local1>" is null. It names the method you tried to call and says which variable was null. The name <local1> is a stand-in. The compiler does not record the names of local variables in the .class file unless asked. Ask it with the -g option, and the real name appears:

Terminal, in code/m06-strings
> javac -g NullDemo.java
> java NullDemo
null
Nickname: null
true
false
0
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "nickname" is null
	at NullDemo.main(NullDemo.java:12)

When you see a NullPointerException, go to the line in the stack trace and look for the variable that could be null on that line. Then ask where it should have been given an object. Lesson 8 returns to null with objects of your own, and lesson 17 shows how to deal with the exceptions it causes.

The mistakes at a glance

The errors you are most likely to meet fit one of these rows. Each one links to the section that explains and demonstrates it.

What you seeLikely causeSection
A string method seems to do nothingThe returned string was discardedStrings never change
Equal-looking strings, but == is falseTwo objects with the same charactersSame object or same characters?
StringIndexOutOfBoundsException with a position equal to the lengthOff by one: the last valid index is length() - 1Asking a string to do something
StringIndexOutOfBoundsException mentioning -1An indexOf that found nothingFinding and cutting
cannot find symbol ... variable lengthParentheses missing on a method callAsking a string to do something
incompatible types or bad operand types with char and StringSingle and double quotes mixed upCharacters
bad operand types for binary operator '<' on two strings< and > are for numbers; use compareToSame object or same characters?
method length in class String cannot be applied to given typesStatic style used for an instance methodAsking a string to do something
char cannot be dereferencedA method called on a char, which is not an objectCharacters
A letter plus a letter prints a numberTwo char values added as numbersCharacters
NumberFormatExceptionText is not a whole number for parseInt: spaces, decimals, wordsText to numbers and back
IllegalFormatConversionException or MissingFormatArgumentExceptionSpecifier and value disagreeFormatting output
NullPointerExceptionA method was called on nullnull: a reference to nothing

Exercises

Each exercise has a folder waiting in work/m06-strings/ in your course kit. Five of the six ask for a static method with an exact header, as in lesson 5. A hidden test program will call your method with a range of arguments, so do not change the name, the parameter types or the return type. You may add a main of your own to try things out; the test program does not use it. Open a hint only after a real attempt.

warm-up

Exercise 6.1 · Initials

Work in work/m06-strings/ex1-initials/ in your course kit

Write a class Initials in Initials.java with this method:

static String initials(String fullName)

The argument is a first name, one space, and a surname, such as "Ada Lovelace". It may be in any mix of upper and lower case. Return the two initials in capitals, each followed by a full stop.

  • Do not use a loop. Find the space with indexOf and cut out each initial with substring.
  • The method returns the answer; it does not print it.

The test program called the method like this:

Sample calls and results
initials("Ada Lovelace") returns "A.L."
initials("grace hopper") returns "G.H."
initials("alan Turing") returns "A.T."
initials("Q X") returns "Q.X."
Hint 1

Two pieces of information locate everything you need: position 0, and the position of the space. What is the position of the first letter of the surname, relative to the space?

Hint 2

A method that changes case does not change the string it is called on; it returns the result. If lower-case input such as "grace hopper" fails your test, look at where the result of that call goes.

To check it, run python check.py m06 ex1 in your course kit folder.

core

Exercise 6.2 · Receipt line

Work in work/m06-strings/ex2-receipt-line/ in your course kit

Write a class Receipt in Receipt.java with this method:

static String line(String item, String quantity, String unitPrice)

The quantity and the price arrive as text, as if read from somewhere. Convert them, work out the line total (quantity times unit price), and return one line of a receipt, laid out in these columns, left to right:

  • the item name, left-aligned in 12 columns;
  • the quantity as a whole number, right-aligned in 3 columns;
  • the text x (a space, the letter x, a space);
  • the unit price with 2 decimals, right-aligned in 6 columns;
  • the text = (a space, an equals sign, a space);
  • the line total with 2 decimals, right-aligned in 7 columns.

Build the string with String.format. You do not need to deal with text that is not a number. Each call below passes text for all three arguments, and the result is printed on the line after it. A ruler line at the top lets you count the columns:

Sample calls and results
0         1         2         3
0123456789012345678901234567890123
line("Notebook", "3", "2.5") returns:
Notebook      3 x   2.50 =    7.50
line("Pen", "12", "0.35") returns:
Pen          12 x   0.35 =    4.20
line("Stapler", "1", "12") returns:
Stapler       1 x  12.00 =   12.00
line("Paper clips", "100", "0.02") returns:
Paper clips 100 x   0.02 =    2.00
Hint 1

Parse first, into an int and a double, and give them names. Then write the format string one column at a time, choosing the specifier for each: text, whole number or decimal.

Hint 2

If you see an IllegalFormatConversionException, read its message: it names the specifier and the type of the value that did not fit.

To check it, run python check.py m06 ex2 in your course kit folder.

core

Exercise 6.3 · Palindrome

Work in work/m06-strings/ex3-palindrome/ in your course kit

A palindrome reads the same forwards and backwards once you ignore case and everything that is not a letter or digit. Write a class Palindromes in Palindromes.java with this method:

static boolean isPalindrome(String text)
  • Letters are compared without regard to case, and only letters and digits count. Spaces, punctuation and anything else are ignored.
  • Text with no letters or digits at all counts as a palindrome.
  • Loop over the characters with charAt, collect the ones that count in a StringBuilder, and compare the result with its own reverse. Compare contents, not references.

Sample calls:

Sample calls and results
isPalindrome("Racecar") returns true
isPalindrome("A man, a plan, a canal: Panama") returns true
isPalindrome("Hello, world") returns false
isPalindrome("12321") returns true
isPalindrome("!!!") returns true
Hint 1

Build the cleaned text first, in lower case. Once it exists, the question is only whether one string equals another.

Hint 2

Be careful with reverse(). It changes the builder it is called on. Decide what you need to keep, and take it as a string, before you reverse.

To check it, run python check.py m06 ex3 in your course kit folder.

core

Exercise 6.4 · Password rules

Work in work/m06-strings/ex4-password-check/ in your course kit

Write a class Passwords in Passwords.java with this method:

static String check(String password)

It returns the message for the first rule that the password breaks, testing the rules in this order, or "OK" if it breaks none:

  1. fewer than 8 characters: "Too short"
  2. contains any whitespace character (a space, a tab, ...): "Contains a space"
  3. contains no digit: "Needs a digit"
  4. contains no upper-case letter: "Needs an upper-case letter"
  5. contains no lower-case letter: "Needs a lower-case letter"

The messages must be spelt exactly as shown, and a tab gets the same "Contains a space" message as a space. Go through the characters of the password once, with a single loop.

Sample calls and results
check("Tr0ub4dor") returns "OK"
check("Ab1") returns "Too short"
check("correct horse 9Battery") returns "Contains a space"
check("lowercase99") returns "Needs an upper-case letter"
check("UPPERCASE99") returns "Needs a lower-case letter"
check("NoNumbersHere") returns "Needs a digit"
Hint 1

Rules 2 to 5 are questions about the whole password: is there a digit anywhere? A loop cannot answer that until it has seen every character, so let the loop only record what it found, and decide afterwards.

Hint 2

The order of the rules matters: "Ab 1" breaks rules 1 and 2, and must report rule 1. Put the checks in the order the list gives.

To check it, run python check.py m06 ex4 in your course kit folder.

core

Exercise 6.5 · Predict, run, explain

Work in work/m06-strings/ex5-equality-log/ in your course kit

This exercise has no code to write. Your folder contains Comparisons.java, which you must not change, and prediction-log.md, which you must fill in.

work/m06-strings/ex5-equality-log/Comparisons.java
public class Comparisons {
    public static void main(String[] args) {
        String a = "moon";
        String b = "moon";
        String c = "mo";
        String d = c + "on";
        final String e = "mo";
        String f = e + "on";
        String g = new StringBuilder("moon").toString();
        String h = a;

        System.out.println("1: " + (a == b));
        System.out.println("2: " + (a == d));
        System.out.println("3: " + a.equals(d));
        System.out.println("4: " + (a == f));
        System.out.println("5: " + (a == g));
        System.out.println("6: " + a.equals(g));
        System.out.println("7: " + (a == h));
        System.out.println("8: " + (d == g));
        System.out.println("9: " + "MOON".equals(a));
        System.out.println("10: " + "MOON".equalsIgnoreCase(a));
        System.out.println("11: " + (a.compareTo("moor") < 0));
    }
}
  1. Read the program. Without running it, fill in Part 1 of the log: for each of the 11 numbered lines, write true or false and a one-sentence reason.
  2. Compile and run the program. In Part 2, list every line where you were wrong, with what you had misunderstood.
  3. Answer the three questions in Part 3 in your own words.
Hint 1

For each ==, draw the arrows. Which variables lead to the same object? Remember which strings are literals, which were joined while the program ran, and which came from a StringBuilder.

Hint 2

Compare the lines that declare d and f, and the lines that declare c and e. One keyword is the difference. The part of the section Same object or same characters? headed A join the compiler can do early is about exactly this.

To check it, run python check.py m06 ex5 in your course kit folder.

stretch

Exercise 6.6 · Caesar shift

Work in work/m06-strings/ex6-caesar/ in your course kit

A Caesar shift replaces each letter with the letter a fixed number of places further along the alphabet, wrapping round from z to a. Write a class Caesar in Caesar.java with this method:

static String shift(String text, int amount)

In exercise 2.5 you shifted three separate letters; here the same arithmetic is applied to a whole text, with capitals, other characters and negative shifts.

  • Only the letters A to Z and a to z change. Capitals stay capitals and small letters stay small. Every other character, including digits, spaces and punctuation, is copied unchanged.
  • amount can be zero, negative, or larger than 26. A shift of -3 undoes a shift of 3, and a shift of 26 changes nothing.
  • Build the result in a StringBuilder.
Sample calls and results
shift("Hello, World!", 3) returns "Khoor, Zruog!"
shift("xyz XYZ", 3) returns "abc ABC"
shift("Khoor, Zruog!", -3) returns "Hello, World!"
shift("Meet at 9 o'clock", 13) returns "Zrrg ng 9 b'pybpx"
shift("abc", -27) returns "zab"
Hint 1

For a lower-case letter c, the number c - 'a' is its place in the alphabet, counting from 0. Add the amount, wrap it into the range 0 to 25, then add 'a' back and cast to char. Capitals work the same way starting from 'A'.

Hint 2

In Java the remainder of a negative number is negative or zero: run System.out.println(-1 % 26); and look. After the % you may need one more step to bring the result into 0 to 25.

To check it, run python check.py m06 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
Primitive typeA type whose variable holds the value itself, such as int or char.
ObjectA block of memory, created while the program runs, that holds data and can be asked to do things with methods.
ReferenceA value that says where an object is. A reference variable holds one.
Static methodA method that belongs to a class and is called with the class name and a dot from another class, and by its bare name inside its own class: Math.max(3, 8), Integer.parseInt(text).
Instance methodA method called on a particular object, with a dot: word.length().
ImmutableUnable to change after creation. Strings are immutable.
MutableAble to change after creation. A StringBuilder is mutable.
Empty stringThe string "", which has no characters.
Method chainSeveral method calls in a row, each on the result of the one before.
ParseRead text and work out the value it describes, as Integer.parseInt does.
StringBuilderAn object holding characters that can be added to, inserted into and reversed in place.
newThe word that creates a new object and gives back a reference to it. Lesson 8 covers it fully.
Format string, specifierText for printf or String.format containing placeholders that begin with %.
Text blockA multi-line string literal between """ delimiters.
nullA reference that leads to no object.
NullPointerExceptionThe exception thrown when a method is called on null.