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;
There is no console output.

These lines only declare two array variables. They print nothing and do not yet create the arrays themselves.

  1. String[] means “string array”: a place where we can later store several strings.
  2. vaisiai is the name of this future array.
  3. int[] means “integer array”.
  4. temperaturos will be the name of the number array.
  5. Until we assign values or use , 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};
There is no console output.

The arrays are created and filled, but the code contains no println(), so nothing appears in the console.

  1. The array vaisiai stores four different strings under one name.
  2. Braces { } surround the initial values, and commas separate them.
  3. All vaisiai values are strings because the array's type is String[].
  4. The array temperaturos stores four integers because its type is int[].
An array stores values of one type.

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]);
Console output

Obuolys
Bananas

  1. Imagine four numbered fruit boxes.
  2. Java numbers the first box not 1, while 0, so vaisiai[0] is Obuolys.
  3. The index 1 belongs to the pear, while index 2 belongs to the banana.
  4. So the second println() line using vaisiai[2] displays Bananas.
Fruit array indices
The indexElement
0Apple
1Pear
2Banana
3Orange

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]);
Console output

Sultys

  1. The shopping array initially contains bread, milk and cheese.
  2. The index 1 points to the second slot, which stores milk.
  3. The statement pirkiniai[1] = "Sultys" replaces the old value with a new one in the same slot.
  4. 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]);
Console output

4
19

  1. The array stores four temperatures, so temperaturos.length returns 4.
  2. Indices start at zero, so the four element indices are 0, 1, 2, 3.
  3. From length subtract one to get the last element's index: 4 - 1 = 3.
  4. At index 3 the stored temperature is 19, 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]);
Console output

Jonas

  1. new String[3] creates three empty slots for strings.
  2. Their indices are 0, 1, 2.
  3. Jonas is stored in the first slot, Ona in the second and Rūta in the third.
  4. vardai[0] accesses the first slot, so the console displays Jonas.
  5. 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"};
There is no console output.

Both lines create identical city arrays, but neither calls println().

  1. The first form explicitly uses new String[] and then supplies the values.
  2. The second form is shorter. Java infers that it needs to create a String array.
  3. Both arrays contain the same elements in the same order.
  4. When the values are known immediately, the shorter form is usually preferred.
Specify either the size or the values, not both.

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 values:

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]);
Console output

0
false
null

  1. All three arrays are created using new, but we have not yet assigned specific values to them.
  2. An empty int array slot automatically receives the number 0.
  3. An empty boolean slot receives false.
  4. An empty String slot receives null. This means it currently contains no string object.
  5. 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]);
Program result: runtime error

ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

  1. The names array has three elements, so its length is 3.
  2. However, the valid indices are 0, 1, 2, because Java starts counting at zero.
  3. The index 3 would mean the fourth element, but this array has no such slot.
  4. The code compiles successfully, but at runtime Java detects the invalid index and stops the program.
  5. Instead of normal console output, we therefore get ArrayIndexOutOfBoundsException.