java strings - stringbuilder
DESCRIPTION
Strings in Java, StringBuilder, changing Strings...TRANSCRIPT
-
1Strings in Java
2OOP2 - Strings in Java
Strings in Java
String basics String methods Immutability and performance Formatting strings
-
23OOP2 - Strings in Java
String basics
A string in Java is a sequence of characters
Instead of character arrays, Java uses class representationof strings, hiding the internal structure that holds the data
String is one of the basic types, used not only for printingmessages, but also for advanced processing of input data
4OOP2 - Strings in Java
Java String class
String class is located in the default package, java.lang
String class is immutable: once created, a string cannot bechanged
- None of its methods actually change the string!
Additionally, String class is final (i.e. it cannot be extended)
-
35OOP2 - Strings in Java
Strings in Java
String basics String methods Immutability and performance Formatting strings
6OOP2 - Strings in Java
String methods
The String class is the only privileged class in Java
- An object can be created without the new keyword:
- Strings can be concatenated without calling a specialmethod:
In total, there are 15 constructors for creating a stringfrom another string, a character array, a byte array, etc.
The String class and other utility classes provide a big poolof methods, enabling easy string manipulation
-
47OOP2 - Strings in Java
Information methods
int length(): returns the length of this string int indexOf(): several different argument lists enable
searching for a position of a substring in the string fromthe beginning or specified position onwards
int lastIndexOf(): search for the last occurrence of asubstring from the end or specific position backwards
boolean endsWith(String suff) boolean startsWith(String pref) boolean equals(Object anObject) boolean equalsIgnoreCase(String anotherString) int compareTo(String anotherString) int compareToIgnoreCase(String anotherString)
8OOP2 - Strings in Java
Transformation methods Used for producing new string(s) from the original string Simpler methods include:
- String substring(int beginIndex, int endIndex)- String trim()- String concat(String str)- String toLowerCase()- String toUpperCase()
More advanced methods are:- String replace(CharSequence target, CharSequence replacement):
replaces every occurrence of target with replacement- String replaceFirst(String regex, String replacement): replaces the
first occurrence matching the specified regular expression- String replaceAll(String regex, String replacement)- String[] split(String regex): splits the string into sub-strings, using
the specified regular expression as a separator
-
59OOP2 - Strings in Java
Regular expressions
Regular expressions enable short representation of stringswith similar structure
The following constructs can be used to build a regex:- [abc]: characters a, b, and c- [^abc]: any character except a, b, and c (negation)- [a-z]: range- [a-zA-Z]: union of ranges- [a-z&&[^df]]: intersection (a through z, except d and f)- \d: digit, [0-9]- \s: whitespace character- \w: word character [a-zA-Z_0-9]-
10OOP2 - Strings in Java
String manipulation example
-
611OOP2 - Strings in Java
String manipulation example (cont)
Output:
12OOP2 - Strings in Java
Strings in Java
String basics String methods Immutability and performance Formatting strings
-
713OOP2 - Strings in Java
Immutability and performance
Immutable objects are convenient because severalreferences can safely point to the same object- That is, there is no danger of changing the object through
one reference without the others being aware of thechange
Disadvantages: less efficient, as for any change a new stringneeds to be created and the old one thrown away:
str Strings
Strings in Java
14OOP2 - Strings in Java
StringBuilder
A companion of the String class, StringBuilder representsa mutable sequence of characters
The principal operations on a StringBuilder are the appendand insert methods, which are overloaded so as to acceptdata of any type
The class also offers methods similar to those of the Stringclass, e.g. indexOf(), lastIndexOf(), charAt(), length(),replace(), substring(), etc.
In addition, there are methods that employ the mutabilityof StringBuilder, and that cannot be found in the Stringclass: delete(), deleteCharAt(), reverse(), setCharAt(), etc.
-
815OOP2 - Strings in Java
Advantages of using StringBuilder
Because strings are immutable, frequent updates of astring can severely affect the performance
Performance-wise, it is much better to use a StringBuilderin place of a String to store the statement underconstruction
To improve performance even further, the appropriatecapacity of the StringBuilder instance should be set- The capacity determines the size of memory to be pre-
allocated
- The more memory is pre-allocated, the less will therebe need for re-allocation (a slow operation)
- However, the memory should not be wasted!
16OOP2 - Strings in Java
Speed test: StringBuilder vs. String
-
917OOP2 - Strings in Java
Speed test results
Output:
18OOP2 - Strings in Java
Strings in Java
String basics String methods Immutability and performance Formatting strings
-
10
19OOP2 - Strings in Java
Formatting strings
As of version 1.5, Java provides a powerful tool forgenerating formatted outputs
The functionality is available in form of a (but not limitedto):- Static format() method of the String class- System.out.printf() method- New Formatter class
Heavily inspired by the Cs printf() function, stringformatting provides support for:- Layout justification and alignment- Common formats for number, string, and date/time
data- Locale specific output
20OOP2 - Strings in Java
Formatting strings example
Output:
-
11
21OOP2 - Strings in Java
Formatting functions
All mentioned formatting approaches operate in a similarfashion, and accept the same set of input parameters:- Format string: a string which may contain fixed text and
one or more format specifiers
- Argument list (optional): values to be inserted into theformat string
- Locale (optional): an object representing a specificgeographical, political, or cultural region (e.g. forcorrect date-to-string conversion)
22OOP2 - Strings in Java
Format specifiers
Format specifiers determine how the arguments should beformatted and inserted into the destination string
General syntax:
- %[index$][flags][width][.precision]conversion
- Note: specifiers within [ and ] are optional
Index: index of the argument to be used with this specifier- The first argument is 1$, the second 2$, etc.
Flags: a set of characters that modify the output format
- E.g. + indicates always show the sign of thenumber; - means left-justify the output, etc.
-
12
23OOP2 - Strings in Java
Format specifiers (cont)
Width: The minimum number of characters to output
Precision: used to restrict the number of characters- E.g. show up to 3 decimal points
Conversion: indicates how the argument should beformatted
Note: not all specifiers work for all arguments- E.g. the precision cannot be used with date/time data
24OOP2 - Strings in Java
Conversion indicators
There exists around 50 conversion indicators, some ofwhich are:
hour for the 12-hour clocktimeth
hour of the day for the 24-hour clocktimetH
locale-specific short month namedatetb
locale-specific full month namedatetB
hexadecimal integerintegralx
scientific notationfloating pointe
formatted as a decimal numberfloating pointf
decimal integerintegrald
true or falseBooleanb or B
OutputRequired argument typeIndicator
-
13
25OOP2 - Strings in Java
Formatting examples