04 Fundementals - Arrays
04 Fundementals - Arrays
Programs
(Part 2-Reference datatype)
Reference
• Readings
• Chapter 6: Arrays and ArrayLists
• Chapter 19: Searching, Sorting and Big O
Introduction
• You can make an array of ints, doubles, or any other type, but all
the values in an array must have the same type.
• To create the array itself, you have to use the new operator:
counts = new int[4];
values = new double[size];
• Of course, you can also declare the variable and create the
array in a single line of code:
int[] counts = new int[4];
double[] values = new double[size];
Accessing Elements
• When you create an array of ints, the elements are initialized to zero.
• Also, you can initialize array directly in the declration line with known values as:
int[] counts = {1, 2, 3, 4};
• The arrow indicates that the value of counts is a reference to the array. You
should think of the array and the variable that refers to it as two different
things.
• The large numbers inside the boxes are the elements of the array. The small
numbers outside the boxes are the indexes (or indices) used to identify each
location in the array.
• Notice that the index of the first element is 0, not 1, as you might have
expected.
Accessing Elements
• The [] operator selects elements from an array and you can
use the [] operator anywhere in an expression:
counts[0] = 7;
counts[1] = counts[0] * 2; counts[2]++; counts[3] -= 60;
System.out.println("The zeroth element is " + counts[0]);
before
Output:
The zeroth element is 7
After
import java.util.Arrays;
• sort for sorting an array (i.e., arranging elements into ascending order),
• binarySearch for searching a sorted array (i.e., determining whether an array contains a
specific value and, if so, where the value is located),
• toString for returns a string representation of the contents of this array enclosed by [].
Example 1
import java.util.Arrays;
Arrays.sort(intArr);
Output:
Integer Arrays on comparison: false
Example 3
import java.util.Arrays;
Arrays.fill(intArr, intKey);
Output:
Integer Array on filling: [22, 22, 22, 22, 22]