- 7.1 Introduction
- 7.2 Fundamentals of Characters and Strings
- 7.3 Class String
- 7.4 Class StringBuilder
- 7.5 Class Character
- 7.6 Tokenizing Strings
- 7.7 Intro to Natural Language Processing (NLP)-at the Root of Generative AI<sup><a id="fn7_5" href="ch07.xhtml#fn7_5a">5</a></sup>
- 7.8 Objects-Natural Case Study: Intro to Regular Expressions in NLP
- 7.9 Objects-Natural Security Case Study: pMa5tfEKwk59dTvC04Ft1IFQz9mEXnkfYXZwxk4ujGE=
- 7.10 Wrap-Up
7.2 Fundamentals of Characters and Strings
Characters are the fundamental building blocks of Java code. A character literal is an integer value represented as a character in single quotes. For example, 'z' represents the letter z’s integer value, and '\t' represents a tab character’s integer value. A character literal’s value is that character’s integer value in the Unicode character set2 (introduced in Chapter 1). Every program is composed of a sequence of characters that—when grouped meaningfully—are interpreted by the Java compiler as instructions to accomplish a task.
Recall from Section 2.2 that a string is a sequence of characters treated as a single unit that may include letters, digits and various special characters, such as +, -, *, / and $. A string is an object of class String. String literals (stored in memory as String objects) are written as a sequence of characters in double quotation marks, as in:
"John Q. Huang" (a name) "99999 Main Street" (a street address) "Waltham, Massachusetts" (a city and state) "(201) 555-1212" (a telephone number)
You’ve assigned string literals to String variables. The following declaration initializes the String variable color to refer to a String object containing "blue":
String color = "blue";
String Objects Cannot Be Modified
Java treats all string literals with the same contents as one String object with many references to it to conserve memory. None of those references can be used to modify the String because String objects are immutable—the String class does not provide methods that modify a String object’s contents. Each String method we demonstrate in this chapter that appears to modify a String actually returns a new String object containing the modifications, leaving the original unchanged.
Generative AI
1 Prompt genAIs to explain why String objects are immutable, but this is not universally true for all data types.
