Text

Most programs manipulate text in one form or another, and the Java platform defines a number of important classes and interfaces for representing, formatting, and scanning text. The sections that follow provide an overview.

The String Class

Strings of text are a fundamental and commonly used data type. In Java, however, strings are not a primitive type, like char, int, and float. Instead, strings are represented by the java.lang.String class, which defines many useful methods for manipulating strings. String objects are immutable: once a String object has been created, there is no way to modify the string of text it represents. Thus, each method that operates on a string typically returns a new String object that holds the modified string.

This code shows some of the basic operations you can perform on strings:

// Creating strings String s = "Now"; // String objects have a special literal syntax String t = s + " is the time."; // Concatenate strings with + operator String t1 = s + " " + 23.4; // + converts other values to strings t1 = String.valueOf('c'); // Get string corresponding to char value t1 = String.valueOf(42); // Get string version of integer or any value t1 = object.toString(); // Convert objects to strings with toString() // String length int len = t.length(); // Number of characters in the string: 16 // Substrings of a string String sub = t.substring(4); // Returns char 4 to end: "is the time." sub = t.substring(4, 6); // Returns chars 4 and 5: "is" sub = t.substring(0, ...

Get Java in a Nutshell, 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.