The String Class
► The String class( sequence of characters) is commonly used for holding and manipulating strings of text in Java programs.
► An object of the String class represents a string of characters.
► The String class belongs to the java.lang package, which does not require an import statement.
► Like other classes, String has constructors and methods.
► Unlike other classes, String has two operators, + and += (used for concatenation).
Literal Strings
► String literals are enclosed in double quotes (“Hello”)
► All string literals in Java programs, such as “abc”, are implemented as instances of this class.
► are defined by enclosing text in double quotes. “This is a literal String”
► don’t have to be constructed.
► can be assigned to String variables.
► can be passed to methods and constructors as parameters.
► have methods you can call.
Examples
//assign a literal to a String variable
String name = “Robert”;
//calling a method on a literal String
char firstInitial = “Robert”.charAt(0);
//calling a method on a String variable
char firstInitial = name.charAt(0);
Immutability
► Once created, a string cannot be changed: none of its methods changes the string.
► Such objects are called immutable.
► Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.
Advantages
Disadvantages
Less efficient — you need to create a new string and throw away the old one even for small changes.
Empty Strings
Copy Constructors.
► Copy constructor creates a copy of an existing String. Also rarely used.
► Not the same as an assignment.
Methods — length, charAt
Methods — Concatenation
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
► String result = word1 + word2;
//concatenates word1 and word2 “rethink“
► String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
► result += word3;
//concatenates word3 to result “rethinking”
► result += num; //converts num to String
//and concatenates it to result “rethinking2”
Methods — substring
Returns a new String by copying characters from an existing String.
Methods — Find (indexOf)
Numbers to Strings
The StringBuffer Class
► StringBuffer class is a mutable class unlike the String class which is immutable.
► StringBuffer can be changed dynamically.
► String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).
► It automatically expands as needed.
► StringBuffer class objects allow manipulation of strings without creating a new object each time a manipulation occurs.
► StringBuffer Capacity
► Every StringBuffer object has a capacity associated with it. The capacity of the StringBuffer is the number of characters it can hold. It increases automatically as more contents added to it.
► The capacity method returns the number of characters (memory) allocated for the object. If the capacity is surpassed, it is expanded to meet the demand.
► The length method returns the current number of characters stored in the object.
StringBuffer constructors and methods
► new StringBuffer(); Creates new, empty StringBuffer
► new StringBuffer(n); Creates new StringBuffer of size n
► sb=new StringBuffer(s); Creates new StringBuffer with initial value s
► sb.append(x)appends x (any primitive or object type) to end of sb.
► sb.setCharAt(index, c)replaces char at index with c
► sb2 = sb.delete(beg, end)deletes chars at index beg thru end.
► sb.setLength(n)Sets the length of the content to n by either truncating current content or extending it with the null character (‘\u0000’). Use sb.setLength(0); to clear a string buffer.
StringBuffer
► sb.charAt(i) Extracting char from StringBuffer at position I
► sb.substring(start, end)substring from position start to the char before end.
► s = sb.toString(); Returns String
► sb.indexOf(s)Returns position of first (leftmost) occurrence of s in sb.
► sb.lastIndexOf(s)Returns position of last (rightmost) occurrence of s in sb.
► sb.length() length of the string
► sb.reverse() reverses the contents.
StringBuffer Functions
► 1. capacity()
Returns the current capacity of the String buffer.
► 2. length()
Returns the length (character count) of this string buffer.
► 3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
► 4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to “ch”
► 5. toString()
Converts to a string representing the data in this string buffer
► 6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.
► 7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer
► 8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
► 9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
► 10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
► 11. setLength(int newLength)
Sets the length of this String buffer.
► 12. ensureCapacity(n) Increases the capacity, as needed, to the specified amount in the given string buffer object
Advantages of StringBuffer
► StringBuffer is faster than string(when concatenating strings)
► String buffers are safe for use by multiple threads. The methods are synchronized where necessary
► StringBuffer is a thread-safe, mutable sequence of characters. Because of the need to modify strings in place without the overhead of creating many new objects, the StringBuffer class was invented.
► But StringBuffer comes with a performance price, and isn’t necessary in single threaded applications
The StringBuilder Class
► StringBuilder objects are like String objects, except that they can be modified.
► Internally, these objects are treated like variable-length arrays that contain a sequence of characters.
► At any point, the length and content of the sequence can be changed through method invocations.
► In simple programs,if you need to concatenate a large number of strings, appending to a String,StringBuilder object is more efficient.
► StringBuilder was added in Java 5.
► It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble.
► For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.
► No imports are necessary because these are both in the java.lang package.
Length and Capacity of StringBuilder
► The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.
► Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated.
► The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.
StringBuilder Constructors
► StringBuilder() : Creates an empty string builder with a capacity of 16 (16 empty elements).
► StringBuilder(int initCapacity) : Creates an empty string builder with the specified initial capacity.
► StringBuilder(String s) : Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.
► StringBuilder sb = new StringBuilder(); // creates empty builder, capacity 16
StringBuilder Methods
► sb.append(“Greetings”); // adds 9 character string at beginningwill produce a string builder with a length of 9 and a capacity of 16
► void setLength(int newLength) Sets the length of the character sequence. If newLength is less than length(), the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added at the end of the character sequence.
► void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.
► A number of operations can increase the length of the character sequence in the string builder so that the resultant length() would be greater than the current capacity(). When this happens, the capacity is automatically increased
► The principal operations on a StringBuilder that are not available in String are the append() and insert() methods
► StringBuilder append(String s)
► StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index) Deletes the specified character(s) in this string builder.
► StringBuilder insert(int offset, String s)
► StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c) Replaces the specified character(s) in this string builder.
► StringBuilder reverse() Reverses the sequence of characters in this string builder. String toString() Returns a string that contains the character sequence in the builder.
StringBuilder vs StringBuffer
► StringBuilder is introduced starting JDK 1.5. There are few differences for them
► StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized.
► StringBuilder does not handle thread-safety issue and none of its methods is synchronized.
► StringBuilder has better performance than StringBuffer under most circumstances.
► So, use StringBuilder if it is not used by multiple threads.
► StringBuilder should work faster than StringBuffer. So ” thread unsafe, fast”.
► StringBuilder is compatible with StringBuffer, but with no guarantee of synchronization, and StringBuilder is a little faster than StringBuffer.
Criteria to choose among String, StringBuffer and StringBuilder
► 1.If your text is not going to change use a string Class because a String object is immutable.It is generally very fast for small text.
► 2.If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
► 3.If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
java.util.StringTokenizer
Purpose
► The java.util.StringTokenizer class is used to break strings into tokens (words, numbers, operators, or whatever).
► A StringTokenizer constructor takes a string to break into tokens and returns a StringTokenizer object for that string. Each time its nextToken() method is called, it returns the next token in that string. If you don’t specify the delimiters (separator characters), blanks are the default.
StringTokenizer Constructors
► StringTokenizer st = new StringTokenizer(s);
► Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.
► StringTokenizer st = new StringTokenizer(s, d);
► Creates a StringTokenizer for the String s using delimiters from the String d.
Common Methods
► Assume that st is a StringTokenizer.
► st.hasMoreTokens() — Returns true if there are more tokens.
► st.nextToken() — Returns the next token as a String.
► st.countTokens() — Returns the int number of tokens.
► This can be used to allocate an array before starting, although it can be inefficient for long strings because it has to scan the string once just to get this number.
► Using a Vector and converting it to an array at the end may be a better choice.
StringTokenizer
► An overloaded constructor allows you to specify the delimiters. For example,
► String str = “A*bunch*of*stars”;
► StringTokenizer st = new StringTokenizer (str,”*”);
► This breaks the string into the tokens separated by the “*” character.
► while (st.hasMoreElements())
System.out.println(“” + ++n +”: “+st.nextElement());
► while(st.hasMoreTokens())
System.out.println(st.nextToken());
String.split ()
► The split() method to the String class is to simplify the task of breaking a string into substrings, or tokens.
► Very simply, it is a method you can call on a string, that causes the string to be chopped up and the bits put into an array. Unlike the StringTokenizer
► Split returns you a chopped up string, and as mentioned in the small text above, it chops up based on delimiters.
► String.split() is only available since JDK 1.4.
► With previous version, java.util.StringTokeniser can be used.
► The split() method takes a parameter giving the regular expression to use as a delimiter and returns a String array containing the tokens so delimited.
Using split(), the first example above becomes
String str = “This is a string object”;
String[] words = str.split (” “);
for (int i=0; i < words.length; i++)
System.out.println (words[i]);
Leave a comment