CIS 160 - Arrays

Objectives

  • Discuss and examine the advantages and disadvantages of arrays
  • Declare arrays
  • Initialize arrays
  • Pass arrays to methods
  • Create Java programs that use arrays
  • Use a StringTokenizer

Arrays

  • arrays are a way of having several variables with the same name
  • the variables are identified by using a subscript
  • arrays are usually used with loops
  • in some programming languages (including Java), all the elements of an array must be of the same base data type
  • declaring an array of 10 integers: int[] num = new int[10];
  • setting the fifth element of the num array to 17: num[4] = 17;
  • displaying the fifth element of the num array: System.out.println(num[4]);
  • the lowest index in an array is 0
  • the highest index in an array is one less than the size of the array (the array's size can be found using: arrayname.length)
  • setting all elements of the num array to 42: for (int i=0; i<num.length; i++) num[i] = 0;
  • see the sample programs for more examples

Using a StringTokenizer

A StringTokenizer lets you break a String up into individual tokens (words). Here is how it works. Please note that StringTokenizer is a convenient way to break up Strings into tokens, but its use in new code is discouraged. The more standard way to break up Strings now would be to use the split method of the String class. The problem with using split is that it uses regular expressions, which we have not covered.

  • import the StringTokenizer class: import java.util.StringTokenizer;
  • create a StringTokenizer initialized with the String you want to break into words: StringTokenizer tok = new StringTokenizer(stringVariable);
  • set up a loop to process all the token in the String: while (tok.hasMoreTokens()) { ... code to process each token ... }
  • within the loop, you can access each token as follows: String word = tok.nextToken();
  • Note: create a new StringTokenizer for each String you want to tokenize

Sample programs

External resource