When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.
In Scala, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.
A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.
Creation:
We create a static array with the new keyword, the element type inside Array[], and the length inside parentheses:
val arrayOfStrings = new Array[String](3)
In this program we created an array named arrayOfStrings that consists of 3 String items.
These 3 items are null (no value given yet) initially.
Creation & Initialization:
There is a way to initialize an array at creation by using the Array(...) factory, listing the values inside the parentheses and putting a comma between each entry, like this:
val arrayOfStrings = Array("AlgoCademy", "coding", "static arrays")
We created an array named arrayOfStrings which consits of 3 String items: "AlgoCademy", "coding" and "static arrays".
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.