Characters Strings and StringBuilder
Characters Strings and StringBuilder
StringBuilder
Character
Instances hold a single character value
Defines methods that can manipulate or inspect single-character
data
String
A class for working with fixed-string data
Unchanging data composed of multiple characters
The String class also provides equalsIgnoreCase and regionMatches methods for
comparing strings. The equalsIgnoreCase method ignores the case of the letters
when determining whether two strings are equal. The regionMatches method
Compares portions of two strings for equality.
String concatenation
You can use the concat method to concatenate two strings. Example,
String s3 = s1.concat(s2);
Since string concatenation is heavily used in programming, Java provides a
convenient way to concatenate strings. You can use the plus sign to concatenate
two or more strings. Example,
String myString = message + “ and ” + “HTML!”;
Recall that you have used the + sign concatenate a number with a
string in the println method. A number is converted into a string and
then concatenated.
Substrings
• setLength() method
– Changes the length of a String in a StringBuilder object
• length property
– An attribute of the StringBuilder class
– Identifies the number of characters in the String contained in the
StringBuilder
• capacity() method
– Finds the capacity of a StringBuilder object
StringBuilder Example
• Using StringBuilder • append() method
objects – Adds characters to the end of a
– Provides improved StringBuilder object
computer performance over • insert() method
String objects – Adds characters at a specific
location within a
– Can insert or append new StringBuilder object
contents into
• setCharAt() method
StringBuilder
– Changes a character at a
• StringBuilder constructors specified position within a
– public StringBuilder StringBuilder object
() • charAt() method
– public StringBuilder – Accepts an argument that is
(int capacity) the offset of the character
position from the beginning of
– public StringBuilder a String
(String s) – Returns the character at that
position
StringBuffer