Chapter 3. Strings and Things

3.0 Introduction

Character strings are an inevitable part of just about any programming task. We use them for printing messages for the user; for referring to files on disk or other external media; and for people’s names, addresses, and affiliations. The uses of strings are many, almost without number (actually, if you need numbers, we’ll get to them in Chapter 5).

If you’re coming from a programming language that is at or below C level, you’ll need to remember that String is a defined type (class) in Java—that is, a string is an object and therefore has methods. It is not an array of characters (though it contains one) and should not be thought of as an array. Operations like fileName.endsWith(".gif") and extension.equals(".gif") (and the almost-equivalent ".gif".equals(extension)) are commonplace.1

Java old-timers should note that Java 11 and 12 added several new String methods, including indent(int n), stripLeading()/stripTrailing(), Stream<String> lines(), isBlank(), repeat(int n), and transform(). Java 15 added stripIndent(). Most of these provide obvious functionality; transform allows applying an instance of a functional interface (see Recipe 9.0) to a string and returning the result of that operation.

Although we haven’t discussed the details of the java.io package yet (we will, in Chapter 10), you need to be able to read text files for some of these programs. Even if you’re not familiar with java.io, you can probably see from the examples ...

Get Java Cookbook, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.