Individual
characters in String objects
String
objects are not arrays, therefore we cannot use the square bracket notation
to refer to or change a particular character in a String.
However,
we can use the String class method charAt()
which allows us to find out what character is at
a particular position in a String object.
So
although the String class is very versatile, what we cannot do is something
like the following:
String text = "hello";
char x = text[1];
It
appears to be a sensible way to assign the character variable x
to be equal to the first character in the String
variable text.
However, it is not permissible because text
is an object, not an array. We can, however,
write
String text = "hello";
char x = text.charAt(1);
which has the effect
we wanted to achieve.
Length of String
objects
For the same
reason, if "text" is a String object, we can't get its length by writing
int lengthOfString = text.length;
but we can write
int lengthOfString = text.length
This will return
an integer value, which is the length of the String variable called "text".
The
reason for this is that the class String provides a length()
method, whereas .length
is how we find out the length of an array.
Such
differences between
[1]
and charAt(1),
and length
verses length()
are things are often confusing when first encountered.
However, as you progress in Java programming you will come to understand
why these seemingly arbitrary distinctions occur.
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|