CSCI111: Chapter 15

CSCI111: Strings

API java.lang


String Manipulation

char is a primitive data type. What does that mean for a java programmer?

char initial = 'p';

Note the single quote. Characters take less time to compare than Strings.

hmmm. Consider the java.lang.Character class . Why is this interesting?

You can see the API for java.lang.Strings and java.lang.StringBuffer .
Read These. Discuss use of static (e.g. valueOf)

Do these need to be imported when used in code?

Strings are immutable. What does this mean?

Because of this, old programmers like to use StringBuffer. Here is an example:

Some Info about String Manipulation for the StringBuffer class

The info below is copied from StringBuffers API page
A string buffer implements a mutable sequence of characters.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order.

String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code:

     x = "a" + 4 + "c"
 

is compiled to the equivalent of:

     x = new StringBuffer().append("a").append(4).append("c")
                           .toString()
 

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point.

For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet".

Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger.