Length of an Array

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

strArray[1] = "World" ;    

Length of an Array

Recall these facts about all arrays:

  1. Each element of an array is of the same type.
    • In the example, each element is of type "reference to String".
  2. The length of an array (the number of cells) is fixed when the array is created.
    • In the example, the array is length 8.

Frequent Bug: It is easy to confuse the length of an array with the number of cells that contain a reference. In the example, only two cells contain references to Strings, but strArray.length will be 8.

Here is a section of code that declares and constructs the array, and puts some more Strings into it:

String[] strArray = new String[8] ;  // combined statement

strArray[0] = "Hello" ;
strArray[1] = "World" ;
strArray[2] = "Greetings" ;
strArray[3] = "Jupiter" ;

QUESTION 4:

Must all the Strings in the array be of the same length?