Main Page

Previous Next

Arrays of Characters

All our arrays have been numeric so far. You can also have arrays of characters. For example, we can declare an array variable of type char[] to hold 50 characters with the statement:

char[] message = new char[50];

We could also define an array of type char[] by the characters it holds:

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 like 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 collection of characters, which is what it is. What we really need is something that is a bit more integrated – something that looks like a message, but still gives us the ability to get at the individual characters if we want. What we need is a String.

Previous Next
JavaScript Editor Java Tutorials Free JavaScript Editor