0% found this document useful (0 votes)
3 views23 pages

String Lecture

Chapter 10 discusses the String class in Java, highlighting its immutability and the concept of interned strings for memory efficiency. It covers string manipulation methods such as replace, split, and the use of regular expressions for pattern matching. Additionally, it introduces StringBuilder and StringBuffer as flexible alternatives for string manipulation, along with examples of their usage.

Uploaded by

Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views23 pages

String Lecture

Chapter 10 discusses the String class in Java, highlighting its immutability and the concept of interned strings for memory efficiency. It covers string manipulation methods such as replace, split, and the use of regular expressions for pattern matching. Additionally, it introduces StringBuilder and StringBuffer as flexible alternatives for string manipulation, along with examples of their usage.

Uploaded by

Mohamed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Chapter 10 Thinking in Objects

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
The String Class
Constructing Strings

String newString = new String(stringLiteral);

String message = new String("Welcome to Java");

Since strings are used frequently, Java provides


a shorthand initializer for creating a string:

String message = "Welcome to Java";


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
animation
The String Class
Strings Are Immutable
String s = "Java"; Does the following code change
s = "HTML"; the contents of the string?

After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"

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";

System.out.println("s1 == s2 is " + (s1 == s2)); s2 : String


System.out.println("s1 == s3 is " + (s1 == s3));
A string object for
"Welcome to Java"

display A new object is created if you use the


s1 == s2 is false new operator.
If you use the string initializer, no new
s1 == s3 is true object is created if the interned object is
already created.

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"

Java check the contents of all the created


strings and since “Welcome to Java” is
already, exist it assigns the reference of s3 to
the same string as s1.

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");

"Java is fun".matches("Java.*"); (matches) can match zero or


any number of characters (.*)
"Java is cool".matches("Java.*");
"440–02–4534".matches("\\d{3}–\\d{2}–\\d{4}")
(matches) can match patterns.
(\\d) represents one digit and (\\d{3})
represents 3 digits

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.

String s = "a+b$#c".replaceAll("[$+#]", "NNN");


System.out.println(s);

The output is aNNNbNNNNNNc.

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.

String[] tokens = "Java,C?C#,C++".split("[.,:;?]");

for (int i = 0; i < tokens.length; i++)


System.out.println(tokens[i]);
The output is delimiters
Java
C
C#
C++
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Convert between Strings and Arrays
A string can be converted into an array and vice versa
From String to Array (toCharArray method) J chars
char[] chars = "Java".toCharArray(); a
v
a
From Array to String
(String(char[]) constructor or the valueOf(char[]) method)
String str = new String(new char[]{'J', 'a', 'v', 'a'});
or,
String str = String.valueOf(new char[]{'J', 'a', 'v', 'a'});

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

For example, to convert a double value 5.44 to a string, use


String.valueOf(5.44).
The return value is a string consisting of the characters '5', '.',
'4', and '4'.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Formatting Strings
The String class contains the static format method to
return a formatted string.
The syntax to invoke this method is:
String.format(format, item1, item2, ..., itemk);
This method is similar to the printf method except that the
format method returns a formatted string, whereas the printf
method displays a formatted string.
Example
String s = String.format("%7.2f%6d%-4s", 45.556, 14, "AB");
System.out.println(s);
Right justification Left justification
Output
45.56 14AB
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
StringBuilder
and StringBuffer
The StringBuilder/StringBuffer class is an alternative to the
String class. In general, a StringBuilder/StringBuffer can be
used wherever a string is used. StringBuilder/StringBuffer is
more flexible than String. You can add, insert, or append new
contents into a string buffer, whereas the value of a String
object is fixed once the string is created.
java.lang.StringBuilder StringBuilder Constructors

+StringBuilder() Constructs an empty string builder with capacity 16.


+StringBuilder(capacity: int) Constructs a string builder with the specified capacity.
+StringBuilder(s: String) Constructs a string builder with the specified string.

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");

stringBuilder.insert(11, "HTML and "); stringBuilder=“Welcome to HTML and Java”

Welcome Java
stringBuilder.delete(8, 11)
Welcome o Java
stringBuilder.deleteCharAt(8)
stringBuilder.reverse() avaJ ot emocleW

stringBuilder.replace(11, 15, "HTML") Welcome to HTML

stringBuilder.setCharAt(0, 'w') welcome to Java

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);
}

You might also like