|
JavaFAQ Home » Java Lessons by Jon Huhtala

The Java Lesson 17
The String
class
Overview
Java does not have a primitive
data type for storing string data, such as "Java
is fun". It does, however, provide an instantiable String class that may be used to
construct String objects.
Such objects encapsulate a constant string and numerous instance methods that
support processing of the string.
The String
class
-
Is part of the java.lang package. This package
is automatically available so no import statement is needed to use the String class.
-
Is an extension of the Object class. This means a
String is an Object and inherits all the
features of the Object
class. The implications of class inheritance will be covered in a later
lesson.
A string literal, such as
"abc", is implemented as an instance of
the String class. It is
placed in a memory area known as the literal pool. When two or more string
literals have the same value, the compiler generates only one String object that is shared.
String jobTitle = new String("clerk");
instantiates a String object having a value of
"clerk" and assigns it to jobTitle. Whenever the keyword
new is specified, a new
object having its own memory space will be created in a memory area known as
the heap as shown by this diagram:
|
|
Heap Space |
|
|
Literal Pool |
|
|
|
|
|
|
|
jobTitle |
-> |
|
|
|
|
A new String object has been created on the heap that
has the same string value as the String object in the literal pool. Any references involving
jobTitle will access the
object on the heap.
Because string literals are
implemented as String
objects, many programmers prefer to not create another object and simply
assign the string literal to the object reference as follows:
String jobTitle = "clerk";
In this case, no heap space is
used as shown by the following diagram:
|
|
Heap Space |
|
|
Literal Pool |
|
|
|
|
|
|
|
|
|
|
jobTitle |
-> |
|
It is important to understand
the difference between the two techniques.
-
Does not permit the value of
its string to be changed. Once instantiated, a String object is immutable. It can, however, be
shared. For example, consider the following statements:
String x = "abc"; String y = "abc";
Because the string literals are
identical, the compiler creates one String object for "abc"
in the literal pool. It is then assigned to both x and y.
|
Method |
Usage |
|
charAt() |
Returns the character at the specified
index within the string where the first character has an index of
0 |
|
compareTo() |
Performs a case-sensitive comparison of
the value of this string to the value of another String object to
determine which comes first alphabetically |
|
concat() |
Concatenates the specified string to the
end of this string to create another String object |
|
equals() |
Performs a case-sensitive comparison of
the value of this string to the value of another String object to
determine if they are equal |
|
equalsIgnoreCase() |
Compares the value of this string to the
value of another String object with both strings viewed as having the
same case |
|
indexOf() |
Returns the index of the first occurrence
of a specified search character or substring within this string
(overloaded) |
|
lastIndexOf() |
Returns the index of the last occurrence
of a specified search character or substring within this string
(overloaded) |
|
length() |
Returns the character length of this
string |
|
replace() |
Replaces all occurrences of a specified
character in this string with another character to create another
String
object |
|
substring() |
Extracts a substring from this string to
create another String object |
|
toLowerCase() |
Converts all characters of this string to
lowercase to create another String object |
|
toUpperCase() |
Converts all characters of this string to
uppercase to create another String object |
|
trim() |
Removes all white space characters (spaces
and TABs) from both ends of this string to create another String
object |
Many of these methods are overloaded to accept different parameter values.
Also notice that methods that appear to modify the string actually return
another String object
(because String objects
are immutable).
Consult Java API documentation for more details.
- Has special support for concatenation and conversion of primitive data
types to their string equivalent within the Java language. Whenever the '+' sign is coded after a string
literal or a String
object reference, it means that the second operand is to be converted to a
string (if it isn't one already) and appended to the first string to create a
new String object. That
is why you have been able to code statements such as
System.out.println("Value
is " + xyz);
The second operand (xyz) is converted to a string and appended to "Value is ". The
resulting string is then passed to the println() method to be displayed. The following would also have
worked:
String temp = "Value is " +
xyz; System.out.println(temp);
- Can trap unwary programmers who incorrectly test two strings for equality.
The correct way to test for equality is to use the equals() method. For example, if stringA and stringB are String class objects, you
should test them for equality by coding either of the following expressions:
stringA.equals(stringB)
or
stringB.equals(stringA)
A common mistake is to code the expression
stringA ==
stringB
which compares the object references and NOT the objects they reference.
The following code, for example, would say that the objects have different
values:
String x = "abc"; String
y = new String("abc"); if (x == y) System.out.println("They
have the same value"); else System.out.println("They have
different values");
Because x references
the object in the literal pool and y references an object on the heap, x and y are not equal even though the strings they reference have
identical values.
The following code would say that the objects have the same value:
String x = "abc"; String
y = new String("abc"); if (x.equals(y))
System.out.println("They have the same value"); else
System.out.println("They have different
values");
Sample program
The following program uses some methods of the String class to count the number of times a
specified character appears within a string entered by the user.
public class App {
public static void main(String[] args) {
//
Variables for holding input data.
String
buffer; char find; String
again;
// Loop to process one string search
request.
do {
// Prompt for and read input data.
Utility.separator(50, '~');
System.out.print("Enter the string to be searched:
"); buffer =
Keyboard.readString();
System.out.print("Enter the character to be counted:
"); find =
Keyboard.readChar();
// Local variables
used in searching and counting.
int
fromIndex = 0; int
foundIndex; int count =
0;
// Loop to find and count all
occurrences of the character // within the
string.
do
{
// Search for the next
occurrence of the character. The
search // will begin at the
location specified by
fromIndex.
foundIndex =
buffer.indexOf(find,
fromIndex);
// If the
character was found, increment the counter and
set // fromIndex to continue the
search at the next character
position.
if (foundIndex
>= 0) {
count++; fromIndex =
foundIndex + 1;
} } while (foundIndex >= 0); // Continue
looping if character is found.
//
Display how many characters the string contains and how
many // times the search character occurs
within the string.
Utility.skip(); System.out.println(" The
string has " + buffer.length() + "
characters"); System.out.println(" '" +
find + "' occurs " + count + "
time(s)");
// Ask the user if they want
to search another string.
Utility.skip(); System.out.print("Again?
("YES" or "NO"): "); again =
Keyboard.readString(); } while
(again.equalsIgnoreCase("YES")); // Loop as requested
} }
Notes:
-
The sample declares a String object reference
(buffer) for the string
to be searched and a char variable (find) for the character to be found. Values for these are read
from the user. Note that the readString() method of my Keyboard class returns a String object.
-
To count how many times the
character occurs within the string, a loop is performed that relies on the
indexOf() method. This
String class method
returns either the index of the next occurrence a specified character within
a string, or -1 if the specified character is not found. The program's loop
begins the search at the first character location (it has an index of 0). If
the search character is found, it is counted and the search resumes at the
next character position. Otherwise, the loop ends.
-
After counting the number of
occurrences of the search character, the results of processing the string
are displayed. The length() method of the String class provides an easy way to display the number of
characters in the string.
-
In asking the user if they
want to process another string, a String object is read and assigned to again. Its value is tested using the equalsIgnoreCase() method so
that they can reply "YES" in any form of capitalization to continue.
Lab exercise for Ferris
students
E-mail your answers to this
assignment no later than
the due date listed in the class schedule.
Review questions
-
Assuming that all unseen
code is correct, what will result from attempting to compile and execute the
following code? The line numbers are for reference purposes only.
1 2 |
String x
= "abcdefg"; System.out.println("Value is: " +
x.charAt(3)); |
-
Compilation will fail at
line 1
-
Compilation will fail at
line 2
-
Compilation will succeed
but a runtime error will occur
-
Compilation will succeed.
The message "Value is: c" will be
displayed.
-
Compilation will
succeed. The message "Value is:
d" will be displayed.
-
Assuming that all unseen
code is correct, what will result from attempting to compile and execute the
following code? The line numbers are for reference purposes only.
1 2 3 4 5 6 7 |
String x
= "abc"; String y = new String(x); String z = y; if
(z.equals(x)) System.out.println("They are
equal"); else System.out.println("They are
different"); |
-
Compilation will fail at
line 2
-
Compilation will fail at
line 3
-
Compilation will fail at
line 4
-
Compilation will succeed.
The message "They are equal" will be
displayed.
-
Compilation will
succeed. The message "They are
different" will be displayed.
-
Assuming that all unseen
code is correct, what will result from attempting to compile and execute the
following code? The line numbers are for reference purposes only.
1 2 |
String x
= new String("abcde"); System.out.println("Result: " +
x.substring(x.length() -
2)); |
-
Compilation will fail at
line 1
-
Compilation will fail at
line 2
-
Compilation will succeed
but a runtime error will occur
-
Compilation will succeed.
The message "Result: de" will be
displayed.
-
Compilation will
succeed. The message "Result:
cde" will be displayed.
-
Assume that x is the object reference of a String object having the string value "abc". What value will the string have after
executing the following statement?
x.toUpperCase();
-
The statement will not
compile
-
The statement will compile
but a runtime error will occur
-
"abc"
-
"Abc"
-
"ABC" Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|