您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 19

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

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg