Strings
as objects
An
object of class String (note the capital 'S' since this is a class identifier)
stores a sequence of characters. New String objects can be created to have
the value of the joining together of two or more existing strings. New
String objects can also be created to have the value of some modified existing
String object. Strings are objects (not primitive data types) ?and so
one must think in object terms of Classes, instance objects, methods and
messages
In
the same way that numbers like 2 and 3 are assumed to be integers, and
numbers like 2.1 and 3.6 are assumed to be floating point numbers (with
an integer and a fractional part), anything in double quotes is assumed
by the Java compiler to be a String. So we can write:
String text = "hello";
or
String text = new String("hello");
Which
creates a new String object and sets it equal to the text "hello". This
is a slightly different way of representing text to the character array
method described in the previous section.
We can also concatenate
('add') strings together to form a new String object, so this line:
String text = new String("hello" + " " + "there");
results in the String
object called "text" being set equal to the text "hello there".
Since
Strings are objects, normally they are manipulated by means of methods
(described in the next unit). So, for example, this line:
newText = text.substring(1, 3);
will
make the String called newText equal to the first, second and third characters
from the String called "text".
There
are many other methods that can be carried out on Strings; see Deitel &
Deitel and the Java documentation for full details.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|