String Lecture
String Lecture
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
The String Class
Constructing Strings
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
The String Class
Interned Strings
Since strings are immutable and are frequently used,
to improve efficiency and save memory, the JVM
uses a unique instance for string literals with the
same character sequence. Such an instance is called
interned. For example, the following statements:
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Examples
String s1 = "Welcome to Java"; s1
: String
String s2 = new String("Welcome to Java"); s3
Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
animation
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Trace Code
s1
String s1 = "Welcome to Java"; : String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Replacing and Splitting Strings
java.lang.String
+replace(oldChar: char, Returns a new string that replaces all matching character in
newChar: char): String this string with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String string with the new substring.
+split(delimiter: String): Returns an array of strings consisting of the substrings split by the
String[] delimiter.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Examples
Replacing
"Welcome".replace('e', 'A') returns a new string,
WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string,
WABlcome.
"Welcome".replaceAll("e", "AB") returns a new
string, WABlcomAB.
Splitting
String[] tokens = "Java#HTML#Perl".split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
displays
Java HTML Perl
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Matching, Replacing and Splitting by Patterns
You can match, replace, or split a string by specifying a pattern.
This is an extremely useful and powerful feature, commonly
known as regular expression.
Example
"Java".matches("Java"); (matches) appears to be similar to (equals),
However (matches) is more powerful.
"Java".equals("Java");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Matching, Replacing and Splitting by Patterns
The replaceAll, replaceFirst, and split methods can be used
with a regular expression.
For example, the following statement returns a new string that
replaces $, +, or # in "a+b$#c" by the string NNN.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Matching, Replacing and Splitting by Patterns
For example, The following statement splits the string into an
array of strings delimited by some punctuation marks.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
Convert Character and Numbers to Strings
The String class provides several static valueOf
methods for converting a character, an array of
characters, and numeric values to strings.
Public methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
StringBuilder
and StringBuffer
The StringBuffer class should be used instead of
StringBuilder class when multiple tasks access this
class as it provides Synchronization in order to protect
the data.
In other word, it prevents tasks to access the class
simultaneously (one at a time) as it is more efficient.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
Modifying Strings in the StringBuilder
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
Examples
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Welcome");
stringBuilder.append(' '); stringBuilder=“Welcome to Java”
stringBuilder.append("to");
stringBuilder.append(' ');
0 11
stringBuilder.append("Java");
Welcome Java
stringBuilder.delete(8, 11)
Welcome o Java
stringBuilder.deleteCharAt(8)
stringBuilder.reverse() avaJ ot emocleW
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
The toString, capacity, length,
setLength, and charAt Methods
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
Problem: Checking Palindromes
Ignoring Non-alphanumeric Characters
Write a program that ignores nonalphanumeric characters in checking
whether a string is a palindrome
Solution Steps:
1. Filter the string by removing the nonalphanumeric characters.
A_B%*01&0##BA AB010BA
filter
Nonalphanumeric
characters
2. Obtain a new string that is the reversal of the filtered string.
AB010BA AB010BA
reverse
3. Compare the reversed string with the filtered string using
the equals method.
AB010BA = AB010BA String is a palindrome
compare
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
Problem: Checking Palindromes
Ignoring Non-alphanumeric Characters
import java.util.Scanner; /** Create a new string by eliminating nonalphanumeric
chars */
public class PalindromeIgnoreNonAlphanumeric {
public static String filter(String s) {
/** Main method */
// Create a string builder
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder();
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: "); // Examine each char in the string to skip alphanumeric char
String s = input.nextLine(); for (int i = 0; i < s.length(); i++) {
if (Character.isLetterOrDigit(s.charAt(i))) {
// Display result
stringBuilder.append(s.charAt(i));
System.out.println("Ignoring nonalphanumeric characters, \nis
}
"
+ s + " a palindrome? " + isPalindrome(s)); // Return a new filtered string
} return stringBuilder.toString(); return a String object
}
/** Return true if a string is a palindrome */
public static boolean isPalindrome(String s) { /** Create a new string by reversing a specified string */
// Create a new string by eliminating nonalphanumeric chars public static String reverse(String s) {
String s1 = filter(s); StringBuilder stringBuilder = new StringBuilder(s);
stringBuilder.reverse(); // Invoke reverse in StringBuilder
// Create a new string that is the reversal of s1
return stringBuilder.toString(); return a String object
String s2 = reverse(s1);
}
// Check if the reversal is the same as the original string }
return s2.equals(s1);
}