JAVA LESSON 12 – ARRAYS

 


INTRODUCTION

In today's free Java lesson, we will look at what arrays are and how they are defined through many simple examples for better understanding of the theory.

DECLARING ARRAYS

In order to better understand how an array can help us programmatically in the logic of our application when added to our code, let's analyze a simple everyday example.

So, imagine that we've been assigned to develop a Java program whose purpose is to record and register students. Generally speaking, there are several ways to approach and solve this problem, but based on the theory you know so far, the answer isn't that simple.

If you assume that each class can't have more than 20 students, you might decide to create 20 different variables, each representing one student. If the class had 50 students, then you might consider creating 50 different variables. You might think you can handle that number of variables—but what if you had to manage a bank's customer base? Would you write 5,000 or 50,000 variables? I think you can now see the seriousness of the problem you're facing.

Also, let’s not forget that beyond just managing variables, there’s also the issue of managing the memory of the system on which your program will run.

An array is defined as a collection of data of the same type, which can be represented using a single name. Each element that belongs to the array has a specific data type (the same as that of the array), and its position within the array is determined by an index number. Index numbering starts at 0.

To define an array, we need to follow two steps:

1     1. Give the array a name

2     2. Create the array using the keyword new and define its size.

In Java, data will either belong to the primitive types or be a type of object. Arrays are objects, and that's why we don't create a variable but a reference in order to manage them.

Don't worry if you don't yet understand the concept of references and objects in general—we will talk about them very soon in a future section. For now, just accept the syntax for creating an array as it is.

So, how do we define an array? First, we declare the type of data the array will hold, such as int, float, String, etc. Immediately after, we write the square brackets [ ], which essentially notify Java that we are defining an array, and finally, the name of the array. Don’t forget to complete the statement by ending the command with a semicolon (;). For example:

int [ ]students;

Java allows us to declare the square brackets [ ] after the name of the array as well. This is a second alternative way to define an array that is also commonly used.

int students[ ];

So far, we have only defined the reference of the array named students. That is, we have defined a name, but it is not yet connected to any array. This is our next step — to create a new array and specify its size.

To create a new array, we use the keyword new, and immediately after, we specify the number that represents the size of the array.

So, to define a new array that can hold 20 students, we write the following statement:

students = new int[20];

Usually, we don’t define the array in two steps but in one. The reason we used two steps is to help you better understand the theory. So, the code:

int students[];

students = new int[20];

can be replaced with the following line:

int students[ ] = new int[20];

ACCESSING ARRAY ELEMENTS

The above statement creates an array that can hold 20 integers. What remains now is to learn how we can place the students’ exam scores into each of the 20 positions of the array. For this purpose, we use a number called an index. Each array numbers its positions, for which it has allocated memory space, with an integer starting from zero. So, for an array that holds 20 integers, the index numbering will be from 0 to 19.

So, if we want to place the first student's grade in the array, we should write the following code:

students[0]=78;

While for the second student, we could put the grade in the next available position, which is:

students[1]=99;

Inside the computer's memory, we have created this:

A question that everyone often wonders about when seeing such an example is: what values exist in the remaining positions of the array where we have not yet inserted integers? An array is not a primitive type (like int, float, char), but it is an object. That is also why we use the keyword new when creating it.

We haven’t talked about objects yet, and there’s no need to go into many details right now. However, due to this characteristic, each array initializes its empty positions with 0 if it is an array of integers, with 0.0 if it holds doubles, and so on.

If you now wanted to fill an array with some random values, you could use a for loop and complete this task very quickly. Using a for loop again, you could very easily read the values an array contains.

App.java

package com.example;


public class App {


public static void main(String[] args) {

int students[] = new int[5];

System.out.println("# Array without input values #");


for (int i = 0; i < 5; i++) {

System.out.println("index " + i + " has " + students[i] +" as a value");

}


students[2] = 78;

students[4] = 99;


System.out.println("# Array with input values #");


for (int i = 0; i < 5; i++) {

System.out.println("index " + i + " has " + students[i]);

}

}

}

Output

Our example is very simple. We initially define an array that can hold up to 5 integers. Immediately after, using a for loop, we ask to view the default values that exist in the array. The output up to this point shows us that all positions in the array contain the number 0.

In the next step, we insert some values into the array in no particular order, and then we use another for loop to print the values the array contains to the terminal this time.

Pay close attention to the bounds defined in the condition of the for loop. We have set the local variable i to be less than 5 because indexing starts at 0, and in this particular example, it goes up to 4.

If you try to access a value at an index number that is outside the bounds of the array, you will get an ArrayIndexOutOfBounds runtime error from Java.

App.java

package com.example;


public class App {


public static void main(String[] args) {

int students[] = new int[5];


students[2] = 78;

students[4] = 99;

students[5] = 63;

}

}

Output

ARRAY SIZE

To avoid errors like the one shown in the previous example, instead of hardcoding the index numbers in the array condition, we use the length attribute provided by the array itself. So instead of writing i < 5, we write students.length, thus avoiding potential ArrayIndexOutOfBounds errors. Let's see how the previous program could be written using the safer approach with the length attribute.

App.java

package com.example;


public class App {


public static void main(String[] args) {

int students[] = new int[5];

System.out.println("# Array without input values #");


for (int i = 0; i < students.length; i++) {

System.out.println("index " + i + " is " + students[i]);

}


students[2] = 78;

students[4] = 99;


System.out.println("# Array with input values #");


for (int i = 0; i < students.length; i++) {

System.out.println("index " + i + " is " + students[i]);

}

}

}


Output

ARRAY INITIALIZERS

Java allows us, as long as we have a small number of data elements, to define the array and pass the data into it in a single line of code and without using the keyword new. The way we define such an array is as follows:

int [ ]students = {67, 49, 72, 83, 99};

We define an array by declaring its name and the type of data it holds. Inside curly braces, we specify the values we want to assign to the array. The method is simple, but Java requires that both the declaration of the array’s name and the assignment of its values must be done on the same line of code.

App.java

package com.example;


public class App {


public static void main(String[] args) {

int[] odds = { 1, 3, 5, 7, 9 };

System.out.println("odds.length = " + odds.length);


for (int i = 0; i < odds.length; i++) {

System.out.println("odds[" + i + "] = " + odds[i]);

}


String[] daysOfWeek = { "Saturday", "Sunday", "Monday", "Tuesday",

"Wednesday", "Thursday", "Friday" };

System.out.println("daysOfWeek.length = " + daysOfWeek.length);


for (int i = 0; i < daysOfWeek.length; i++) {

System.out.println("daysOfWeek[" + i + "] = " + daysOfWeek[i]);

}

}

}

Output

FOREACH LOOPS

Apart from the for loop, we have another quick way to read values from an array, called the foreach loop. We declare a local variable in the foreach loop with any name we want and the appropriate data type. Then, we use a colon (:), followed by the name of the array. The variable will automatically receive the values of the array one by one.

App.java

package com.example;


public class App {


public static void main(String[] args) {

String[] daysOfWeek = { "Saturday", "Sunday", "Monday", "Tuesday",

"Wednesday", "Thursday", "Friday" };


for (String days : daysOfWeek) {

System.out.println(days);

}

}

}

Output

MULTIDIMENSIONAL ARRAYS

All the examples we have analyzed so far involve one-dimensional arrays. How could we define an array with two or more dimensions? The method is once again simple — we just add as many square brackets ([ ]) as the number of dimensions we want the array to have.

int [ ][ ] courses = new int[3][2];

In reality, we have created this:



Let’s look at a simple example of a two-dimensional array.

App.java

package com.example;

package com.example;


public class App {


public static void main(String[] args) {

int[][] courses = new int[3][2];

courses[1][1] = 10;

courses[2][0] = 20;


for (int row = 0; row < courses.length; row++) {

for (int col = 0; col < courses[row].length; col++) {

System.out.println(courses[row][col]);

}

System.out.println();

}

}

}

Output




Arrays are very useful for us programmers, but this particular type of array has several weaknesses, the most important being that its size cannot be changed once it is defined. This is a major disadvantage.

Think again about the example with the customers of a bank. How large can you initially define your array? 10,000 or 50,000? And if, within a short period, the bank’s customers double, how will you handle this problem? And if the customers do not double, just by defining such a large array, you have reserved a very large portion of your system’s memory without even needing it.

Apart from the memory problem, there are other issues we have to deal with regarding this type of array, such as simultaneous access to data from different objects and performance and speed problems when searching for data.

When we eventually cover the theory of objects, we will be able to talk about the broader category to which arrays belong, called collections, which includes other types of arrays that are more flexible and have more features.

Don’t forget to make a small donation so that this blog can grow even more and have more capabilities for delivering free online lessons.


full-width

Post a Comment

0 Comments