Array of Strings

Having an array of String works both ways - like an array of primitives or like an array of String objects. Since it is a class, you can use new if you want to. Since it is a built-in class that is used so often, you can also skip the new and it will work correctly. This code demonstrates both ways.

Example code using an array of Strings; can you draw it?

    String names[] = new String[5];
    int    i;

    names[0] = "Pippi";
    names[1] = new String("Yambi");
    names[2] = "Patches";
    names[3] = "Toto";
    names[4] = new String("Tuppence");

    for (i = 0; i < names.length; i++)
        System.out.println("names[" + i + "] is: "
            + names[i] + " length is: " 
            + names[i].length());
Here is the output from this code:
    names[0] is: Pippi length is: 5
    names[1] is: Yambi length is: 5
    names[2] is: Patches length is: 7
    names[3] is: Toto length is: 4
    names[4] is: Tuppence length is: 8
Notice: the for loop uses names.length and the println() uses names[i].length() - What do you think is going on in this code?

Try answering these questions:

  1. What class is names?
  2. What class is names[3]?
  3. What is names.length doing?
  4. What is the value of names.length?
  5. What is names[i].length() doing?
  6. What is the value of names[i].length() when i is 4?
  7. How did you know difference between these two uses of length?