Java Reference
In-Depth Information
The StringBuffer Class
Java has another class for representing strings, the StringBuffer class. A String object cannot
be altered because String objects are immutable. If you are working with strings that need
to be altered, the StringBuffer is a flexible alternative.
Strings represented as StringBuffer objects are basically an array of characters, allowing
you to change, insert, or delete individual characters of the StringBuffer. You can also
append characters, change the length of the buffer, view characters at a specific location in
the string, and reverse the order of characters.
This is all accomplished by using the many helpful methods of the StringBuffer class. (In
Chapter 5, “Methods,” you will learn the details of invoking a method on an object.)
References versus Primitive Data
I showed you in the earlier section titled Variables how to declare a variable,
and then we saw some sample programs that used variables of the primitive
data types. However, there is one other type of variable in Java, called a refer-
ence, which is used when the data involved is not a primitive data type. You
saw this initially in the StringDemo program, but I purposely avoided dis-
cussing references at the time because the point of the StringDemo program
was to demonstrate String objects.
Now, I want to focus on the details of references versus primitive types
because understanding references is an essential component of understanding
Java. For example, suppose that you need to allocate memory for a String to
represent someone's name. Your code might look like the following:
String name;
name = “Rich”;
In this example, name is a variable of type String. String is not one of the
eight primitive data types. It is a commonly used class that is a part of the J2SE.
When you declare a variable of a class type, that variable is referred to as a ref-
erence . The term reference is used because a reference refers to an object.
A reference is different from a primitive data type in that a reference does
not contain the actual data of the object that it refers to. Instead, a reference
points to the location in memory where the object is located.
In other words, the name variable above does not contain the string “Rich”.
Instead, “Rich” is somewhere else in memory, and name points to that loca-
tion. This is quite different from the values x and pi, which are primitive data
types. The value 250 is in the 32 bits consumed by x, and the value 3.14159 is in
the 64 bits consumed by pi.
Search WWH ::




Custom Search