Prog 731 Java Topic 3 (Arrays and Arraylists)
Prog 731 Java Topic 3 (Arrays and Arraylists)
HYBRID LEARNING
79 87 94 82 67 98 87 81 74 91
scores
• A particular value in an array is referenced using the array name followed by the index in brackets
• For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a single integer and can be used wherever an integer
variable can be used
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);
boolean[] flags;
flags = new boolean[20];
• For example, if the array codes can hold 100 values, it can be indexed using only the
numbers 0 to 99
• If count has the value 100, then the following reference will cause an exception to be
thrown:
System.out.println (codes[count]);
• It’s common to introduce off-by-one errors when using arrays
problem
• Each array object has a public constant called length that stores the size of the array
• It is referenced using the array name:
scores.length
• Note that length holds the number of elements, not the largest index
• The brackets of the array type can be associated with the element type or
with the name of the array
• Therefore the following declarations are equivalent:
float[] prices;
float prices[];
• An initializer list can be used to instantiate and initialize an array in one step
• The values are delimited by braces and separated by commas
• Examples:
• The signature of the main method indicates that it takes an array of String objects as a parameter
• These values come from command-line arguments that are provided when the interpreter is invoked
• For example, the following invocation of the interpreter passes an array of three String objects into
main:
temp = first;
first = second;
second = temp;
one two
dimension dimensions
value = scores[3][6]
• The array stored in one row or column can be specified using one index