Motivation
for String class
As
you may have found in the first part of this unit, arrays of characters
can be a little fiddly to deal with, since each character element has to
be dealt with individually.
The
text "hello" could be seen as a kind of array. It has 5 elements. Element
0 is the character "h", element 1 is the "e" and so on. This can be written
in Java like this:
char text[] = {'h','e','l','l','o'};
After
this line, the array "text" will contain the five characters that make
up the word "hello". We can read the individual array elements in just
the same way as any other array, e.g.,
char myChar = text[4];
This will make the
character variable called "myChar" contain the character "o".
However,
this is not a very useful way of manipulating text except when we
need to process individual characters. Normally we would use a String object
to work with such text.
The
String class, provided as 'built-in' by the developers of the Java language,
makes working with sequences of characters much easier. The String class
defines methods for many actions, including:
-
finding the length
of a string
-
locating a character
or sub-string within a string
-
concatenating two
strings together to create a new String object
-
converting primitive
types to Strings
-
comparing the values
inside String objects
Since
many tasks where people interact with computers involves working with text
on screen (word processors, databases, document viewing on the internet
etc.) providing a class to make working with sequences of characters makes
a lot of sense.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|