CODE STRUCTURE
Java arrays
An array stores several values of the same type in one variable. Instead of creating a separate variable for each element, we can put them in one numbered dataset.
Declaring an array
An array type is marked with square brackets [] after the element type:
String[] vaisiai;
int[] temperaturos;These lines only declare two array variables. They print nothing and do not yet create the arrays themselves.
String[]means “string array”: a place where we can later store several strings.vaisiaiis the name of this future array.int[]means “integer array”.temperaturoswill be the name of the number array.- Until we assign values or use
new , we only have names, not ready-to-use numbered slots.
An array with initial values
If the values are already known, list them inside braces separated by commas:
String[] vaisiai = {
"Obuolys",
"Kriaušė",
"Bananas",
"Apelsinas"
};
int[] temperaturos = {18, 20, 22, 19};The arrays are created and filled, but the code contains no println(), so nothing appears in the console.
- The array
vaisiaistores four different strings under one name. - Braces
{ }surround the initial values, and commas separate them. - All
vaisiaivalues are strings because the array's type isString[]. - The array
temperaturosstores four integers because its type isint[].
String[] stores strings, while int[] stores integers.
Accessing elements by index
Each element has an index. Java array indices start at 0:
String[] vaisiai = {
"Obuolys", "Kriaušė", "Bananas", "Apelsinas"
};
System.out.println(vaisiai[0]);
System.out.println(vaisiai[2]);Obuolys
Bananas
- Imagine four numbered fruit boxes.
- Java numbers the first box not
1, while0, sovaisiai[0]is Obuolys. - The index
1belongs to the pear, while index2belongs to the banana. - So the second
println()line usingvaisiai[2]displays Bananas.
| The index | Element |
|---|---|
| 0 | Apple |
| 1 | Pear |
| 2 | Banana |
| 3 | Orange |
Changing an array element
Assign a new value to a specific element by specifying its index:
String[] pirkiniai = {"Duona", "Pienas", "Sūris"};
pirkiniai[1] = "Sultys";
System.out.println(pirkiniai[1]);Sultys
- The shopping array initially contains bread, milk and cheese.
- The index
1points to the second slot, which stores milk. - The statement
pirkiniai[1] = "Sultys"replaces the old value with a new one in the same slot. - Printing the second element therefore displays Sultys.
Array length
Property length returns the number of array elements. It is a property, so it takes no parentheses. The last element's index is always length - 1.
int[] temperaturos = {18, 20, 22, 19};
System.out.println(temperaturos.length);
System.out.println(temperaturos[temperaturos.length - 1]);4
19
- The array stores four temperatures, so
temperaturos.lengthreturns4. - Indices start at zero, so the four element indices are
0, 1, 2, 3. - From
lengthsubtract one to get the last element's index:4 - 1 = 3. - At index
3the stored temperature is19, so it appears on the second console line.
Creating an array with new
When the required size is known but values will be added later, create the array using new and the number of slots:
String[] vardai = new String[3];
vardai[0] = "Jonas";
vardai[1] = "Ona";
vardai[2] = "Rūta";
System.out.println(vardai[0]);Jonas
new String[3]creates three empty slots for strings.- Their indices are
0, 1, 2. - Jonas is stored in the first slot, Ona in the second and Rūta in the third.
vardai[0]accesses the first slot, so the console displays Jonas.- An array's size is fixed at creation and cannot be changed later.
Two equivalent initialization forms
// Full form using new
String[] miestai = new String[] {"Vilnius", "Kaunas", "Klaipėda"};
// Shorter and most commonly used form
String[] miestai2 = {"Vilnius", "Kaunas", "Klaipėda"};Both lines create identical city arrays, but neither calls println().
- The first form explicitly uses
new String[]and then supplies the values. - The second form is shorter. Java infers that it needs to create a
Stringarray. - Both arrays contain the same elements in the same order.
- When the values are known immediately, the shorter form is usually preferred.
new String[3] creates an empty array, while new String[] {...} creates an array from the supplied values.
Default values
With new , array slots that have not been filled yet receive default
int[] taskai = new int[3];
boolean[] patikrinta = new boolean[3];
String[] pranesimai = new String[3];
System.out.println(taskai[0]);
System.out.println(patikrinta[0]);
System.out.println(pranesimai[0]);0
false
null
- All three arrays are created using
new, but we have not yet assigned specific values to them. - An empty
intarray slot automatically receives the number0. - An empty
booleanslot receivesfalse. - An empty
Stringslot receivesnull. This means it currently contains no string object. - Java supplies these initial values automatically.
An index outside the array
Accessing an index that does not exist causes a runtime error:
String[] vardai = {"Jonas", "Ona", "Rūta"};
System.out.println(vardai[3]);ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
- The names array has three elements, so its length is
3. - However, the valid indices are
0, 1, 2, because Java starts counting at zero. - The index
3would mean the fourth element, but this array has no such slot. - The code compiles successfully, but at runtime Java detects the invalid index and stops the program.
- Instead of normal console output, we therefore get
ArrayIndexOutOfBoundsException.