Java Reference
In-Depth Information
All the arrays you have defined have contained elements storing numerical values so far. You can also have
arrays of characters. For example, you can declare an array variable of type char[] to hold 50 characters
with the following statement:
char[] message = new char[50];
Keep in mind that characters are stored as Unicode UTF-16 in Java so each element occupies 2 bytes.
If you want to initialize every element of this array to a space character, you can either use a for loop to
iterate over the elements of the array, or just use the fill() method in the Arrays class, like this:
java.util.Arrays.fill(message, ' '); // Store a space in every element
Of course, you can use the fill() method to initialize the elements with any character you want. If you
put '\n' as the second argument to the fill() method, the array elements all contain a newline character.
You can also define the size of an array of type char[] by the characters it holds initially:
char[] vowels = { 'a', 'e', 'i', 'o', 'u'};
This defines an array of five elements, initialized with the characters appearing between the braces. This
is fine for things such as vowels, but what about proper messages?
Using an array of type char[] , you can write statements such as:
char[] sign = {'F', 'l', 'u', 'e', 'n', 't', ' ',
'G', 'i', 'b', 'b', 'e', 'r', 'i', 's', 'h', ' ',
's', 'p', 'o', 'k', 'e', 'n', ' ',
'h', 'e', 'r', 'e'};
Well, you get the message — just — but it's not a very friendly way to deal with it. It looks like a collec-
tion of characters, which is what it is. What you really need is something a bit more integrated — something
that looks like a message but still gives you the ability to get at the individual characters if you want. What
you need is a String .
STRINGS
You will need to use character strings in most of your programs — headings, names, addresses, product
descriptions, messages — the list is endless. In Java, ordinary strings are objects of the class String . The
String class is a standard class that comes with Java, and it is specifically designed for creating and pro-
cessing strings. The definition of the String class is in the java.lang package so it is accessible in all your
programs by default. Character in strings are stored as Unicode UTF-16.
String Literals
You have already made extensive use of string literals for output. Just about every time the println() meth-
od was used in an example, you used a string literal as the argument. A string literal is a sequence of char-
acters between double quotes:
"This is a string literal!"
Search WWH ::




Custom Search