Introduction to arrays
Java arrays allow us to create a contiguous sequence of elements of the same
type. In this sense they are similar to Java String, which is a sequence of
elements of the same type char.
Just like Java Strings, with Java arrays we can:
- obtain the length
- gain access to an individual element
- use the indices 0..length-1 (inclusive)
In addition, with Java arrays we can:
* modify the contents of individual element (not possible in Java String)
Here is a comparison between Java String and Java array:
STRING ARRAY
Creating Creating
String word = "hello"; int[] numbers = {5, 3, 6, 2};
double[] scores = {3.3, 4.0, 2.0};
char[] letters = {'h', 'e', 'l', 'l', 'o'};
String[] words = {"how", "are", "you"};
boolean[] answers = {true, false, false, true};
Getting the length Getting the length
word.length() numbers.length <-- no parentheses ()
scores.length
letters.length
words.length
answers.length
Valid indices Valid indices
0..word.length()-1 (inclusive) 0..numbers.length-1 (inclusive)
Accessing an element Accessing an element
word.charAt( integer-index ) numbers[ integer-index ]
Modifying an element Modifying an element
NOT POSSIBLE int[] numbers = {5, 3, 6, 2};
int x = numbers[0]; // x is now 5
numbers[3] = 2*x; // last element now 10
numbers[1] = numbers[2];
// numbers is now {5, 6, 6, 10}
When the size of the array is known in advance we
can create an array of the given number of elements:
int[] myArray = new int[10]; // myArray has 10 empty slots
int size = myArray.length/2;
int[] yourArray = new int[size]; // yourArray has 5 empty slots
Note that in the examples above we can replace int with any other type before the []:
char[] letters = {'s', 'm', 'i', 'l', 'e', 'y'}; boolean[] answers = {true, false, false, true};
char c = letters[0]; // c is now 's' boolean q1 = answers[0]; // q1 is now true
letters[5] = '!'; // last element now '!' answers[3] = false; // last element now false
letters[0] = letters[4]; answers[0] = answers[3];
// letters is now {'e', 'm', 'i', 'l', 'e', '!'} // answers is now {false, false, false, false}
char[] myArray = new char[10]; boolean[] myArray = new boolean[10];
int size = myArray.length/2; int size = myArray.length/2;
char[] yourArray = new char[size]; boolean[] yourArray = new boolean[size];