CS 1110/1111: Introduction to Programming

Lecture 16

Announcements

Today's topic is not on next week's test, but it is on next homework

Talking Points

Slides from 001 and 002

Arrays are Java's way of storing lists of values. Each array stores only one kind of thing, and when you make them they are of a fixed size (like an egg carton: it can hold a fixed number of eggs). You can either make them empty or full.

int[] numbers = new int[12]; // can hold 12 ints
String[] words = new String[3]; // can hold 3 Strings
double[] constants = { Math.PI, Math.E, Math.sqrt(2), 42.0 }; // can hold 4 doubles, and already does

If you don't provide values, Java fills in 0 for numbers, false for booleans, and null for everything else. null is a special value that means I could talk about an object, but I'm not.

Each spot in an array has an index; these start at 0 (just like for Strings). We index using square brackets. An array with an index acts just like a variable.

System.out.println( numbers[0] );
numbers[1] = (int)(constants[3]);
System.out.println( numbers[1] );
System.out.println( words[2] );
words[2] = "word";
System.out.println( words[2] );
System.out.println( words[2].length );

Arrays also have one field, length. A field is kind of like a method, but you don't use parentheses:

System.out.println( "We can hold " + words.length + " words" );
System.out.println( "The third word has " + words[2].length() + " characters in it" );

You can make a String[] using the split() method:

String example = "bedizeneer";
String[] bits = example.split("e");
System.out.println("there are " + bits.length+" bits");
for(int i = 0; i < bits.length; ++i) {
    System.out.println(i + ": \"" + bits[i] + "\"");
}
Copyright © 2014 by Luther Tychonievich. All rights reserved.