Getting Started
In programming, we often need to work with text, such as names, sentences, or messages. The Java String class is the fundamental tool for representing and manipulating these sequences of characters. This chapter explores how to create strings and use built-in methods to inspect them, extract portions of them, and combine them to form new strings.
What You Should Be Able to Do
Create new
Stringobjects using string literals, constructors, and concatenation.Determine the number of characters in a
Stringusing thelength()method.Extract a portion of a
String(a "substring") using thesubstring()method.Find the position of a specific character or sequence of characters within a
Stringusing theindexOf()method.Understand and explain that
Stringobjects are immutable, meaning they cannot be changed once created.
Key Concepts & Java Implementation
The Core Idea
A String is an object that represents a sequence of characters. In Java, strings are a core part of the language, found in the java.lang package, which is automatically available in every Java program. You can create a string simply by enclosing characters in double quotes, an expression known as a string literal (e.g., "Hello, World!").
The most important conceptual property of Java String objects is that they are immutable. This means that once a String object is created, its sequence of characters can never be changed. Any method that appears to modify a string, such as combining it with another string or extracting a part of it, actually creates and returns a brand new String object with the new value, leaving the original unchanged.
Syntax & Implementation
Creating and Concatenating Strings
You can create strings using literals or by explicitly calling the Stringconstructor, a special method used to initialize a new object. You can combine strings using the + or += operators in a process called concatenation.
// 1. Creating a String with a literal (most common)
String greeting = "Hello";
// 2. Creating a String with the constructor
String name = new String("Ada");
// 3. Concatenation using the '+' operator
// This creates a NEW string "Hello, Ada" and assigns it to message.
// The original "greeting" and "name" strings are not changed.
String message = greeting + ", " + name; // message is now "Hello, Ada"
// 4. Concatenation using the '+=' operator
String phrase = "Java is ";
phrase += "fun!"; // phrase is now "Java is fun!"
Key String Methods
The String class provides several useful methods for examining and manipulating string data. The characters in a string are accessed by their index, which is a zero-based integer position. The first character is at index 0, the second at index 1, and so on.
| Method Signature | Purpose | Java Example |
|---|---|---|
int length() | Returns the number of characters in the string. | String s = "code"; int len = s.length(); // len is 4 |
String substring(int from, int to) | Returns a new string containing characters from index from up to, but not including, index to. | String s = "robot"; String sub = s.substring(1, 4); // sub is "obo" |
String substring(int from) | Returns a new string containing characters from index from to the end of the string. | String s = "computer"; String sub = s.substring(3); // sub is "puter" |
int indexOf(String str) | Returns the starting index of the first occurrence of str. Returns -1 if str is not found. | String s = "banana"; int i = s.indexOf("an"); // i is 1 |
Annotated Java Examples
// Example demonstrating length(), substring(), and indexOf()
String text = "AP Computer Science";
// Using length()
int len = text.length(); // len is 19
// Using substring(from, to)
// Extracts the word "Computer"
// Starts at index 3, ends right before index 11
String middleWord = text.substring(3, 11); // middleWord is "Computer"
// Using substring(from)
// Extracts the word "Science"
// Starts at index 12 and goes to the end
String lastWord = text.substring(12); // lastWord is "Science"
// Using indexOf()
// Find the position of the first space
int firstSpace = text.indexOf(" "); // firstSpace is 2
// Find the position of a substring
int sciencePos = text.indexOf("Science"); // sciencePos is 12
// indexOf() returns -1 if the substring is not found
int javaPos = text.indexOf("Java"); // javaPos is -1
Tracing & Analysis
Execution Trace
Let's trace the execution of code that extracts the domain name from an email address.
Code:
String email = "student@example.com";
int atSymbolPos = email.indexOf("@");
String domain = email.substring(atSymbolPos + 1);
Trace:
String email = "student@example.com";- A
Stringobjectemailis created with the value"student@example.com".
- A
int atSymbolPos = email.indexOf("@");The
indexOfmethod is called onemail.It searches for
"@"and finds it at index 7.The variable
atSymbolPosis assigned the value7.
String domain = email.substring(atSymbolPos + 1);The expression
atSymbolPos + 1evaluates to7 + 1, which is8.The
substringmethod is called onemailwith a starting index of8.A new
Stringis created containing characters from index 8 to the end.The variable
domainis assigned the value"example.com".
Analysis
Notice how String immutability works. After the trace, the original email string "student@example.com" remains completely unchanged. The substring method did not modify email; it returned a new String object which we stored in the domain variable. This behavior is predictable and safe, preventing accidental modification of strings that might be used elsewhere in a program.
Java Syntax Quick-Reference
A compact reference for the String methods covered in this topic.
| Method | Description |
|---|---|
int length() | Returns the count of characters in the string. |
String substring(int from, int to) | Returns a new string from index from up to (but not including) index to. |
String substring(int from) | Returns a new string from index from to the end. |
int indexOf(String str) | Returns the index of the first occurrence of str, or -1 if not found. |
new String(str) | A constructor that creates a new String object from another string. |
+ and += | Operators used for string concatenation. |
Core Code Examples & Terminology
String: An object representing an immutable sequence of characters.
Immutable: A property of an object meaning its state cannot be modified after it is created. For strings, this means its character sequence is fixed.
Index: A zero-based integer representing a character's position in a string. The first character is at index 0.
Concatenation: The process of combining two or more strings to create a new, single string.
Substring: A portion of a string, represented as a new
Stringobject.Core Snippet 1 (Extracting a Substring):
String data = "INFO:Success"; String status = data.substring(5); // status becomes "Success"This code extracts a new string starting from index 5 to the end of the original string.
Core Snippet 2 (Finding a Position):
String message = "Error at line 42"; int position = message.indexOf("line"); // position becomes 9This code finds the starting index of the first occurrence of the substring
"line".Core Snippet 3 (Concatenation):
String firstName = "Grace"; String lastName = "Hopper"; String fullName = firstName + " " + lastName; // fullName is "Grace Hopper"This code creates a new string by combining two existing strings and a literal space.
Core Skill Check
Code Tracing: What is the final value of
resultafter this Java code runs:String s = "programming"; String result = s.substring(s.indexOf("r"), 8);?- Answer:
"rogram"
- Answer:
Debugging: Identify the runtime error in this Java code:
String word = "Java"; char c = word.charAt(4);.- Answer:
StringIndexOutOfBoundsException. The valid indices for"Java"are 0, 1, 2, and 3. Index 4 is out of bounds.
- Answer:
Application: Write a single line of Java code that creates a new string containing the first character of the string
String str = "example";.- Answer:
String firstChar = str.substring(0, 1);
- Answer:
Common Misconceptions & Errors
Forgetting
Stringis Immutable: Believing that methods likesubstring()or concatenation change the original string. They always return a new string, leaving the original untouched.substring(from, to)is Inclusive ofto: Thesubstringmethod with two arguments extracts characters from thefromindex up to, but not including, thetoindex.s.substring(0, 5)gets characters at indices 0, 1, 2, 3, and 4.Off-by-One Errors with Indices: Forgetting that string indices are 0-based. In a string of
length()10, the valid indices are 0 through 9. Accessing index 10 will cause an error.Confusing
indexOfReturn Values:indexOfreturns0if the substring is found at the very beginning of the string. It returns-1only when the substring is not found at all.
Summary
The String class is Java's primary tool for handling text. A key feature of String objects is their immutability—their contents cannot be changed after creation. Instead, methods that manipulate strings, such as concatenation (+) or substring(), produce new String objects. The length() method provides the character count, indexOf() locates substrings by their starting position, and substring() extracts a portion of a string. Mastering these methods is essential for performing common text-processing tasks, from parsing user input to formatting output.