Java Beginner: Lesson 8

Array


After haveing some knowledges about data types, if condition and loops we will see arrays in this lesson. We will abandon the HelloWorld application that we have used previously and we will create a new one. If you need help on how to create a new project refresh your memory from lesson 1.

I will name the project on this lesson Array, you can name it whatever you would like to. Being that we have seen loops in previous lessons we will make a simple iteration into an array and edit some elements of the array.

Array in java is a data structure which can hold inside it elements of the type which we declare that it can hold. For example, we will have a data structure which can hold integers if we declare an array as shown in the example bellow:

Example code:

But how many elements can this data structure hold? We have not determined it yet because we have just declared the array and not initialized or instantiated it. There are different ways to give a value to this array as shown bellow:

Example code:

or

Example code:

or

Example code:

In the first case we just instantiate but not initialize the array, in the second case we instantiate and initialize the array at the same time, same as in the third case. We will talk about instantiation and initialization in the upcoming lessons when we will deal with objects. In the first case we determine directly the size 5 of the array, in the other 2 cases is the compiler that finds out the size of the arrays by let say "counting" the elements that we have given to it.

The difference between the second and the third way of the initialization of the array is that the second way we can use only when we declare the array, while the third way we can use to declare a new instance with the same name. We will call in the lesson of the objects about the instances in java as well.

We can override the values in specific indexes in the array as follow:

Example code:

The problem with the arrays is that once their size is set it can not change for that instance, this is the reason why usualy we see the ArrayList-s much more used than arrays. We will cover ArrayList-s, or List-s in general in the intermediate level of java.

Bellow you have the example code summarizes what is explained above.

Example code:

From the code above you can notice that from the myArray object through dot(.) operator can be accessed a variable with name length, this variable gives us the length of the array in the moment we access it.

In the figure 1 you can see the execution of the code above.


Figure 1: Array example running


(please report broken link in the comment)

Comments

Popular posts from this blog

Free host and domain

C++ Beginner: Lesson 3 - Simple calculator

C++ Beginner: Lesson 4 - Tic Tac Toe game