Types of Arrays in Java
Introduction to Arrays in Java
In Java, an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Types of Arrays in Java
There are two types of Arrays in Java; they are:
- Single Dimensional Array
- Multi-Dimensional Array
Let's take a closer look at both of these.
Single Dimensional Array
Single dimensional arrays are the simplest form of arrays in Java that store a sequence of elements of the same type. You can think of these like a single row in a table.
To declare a single-dimensional array, you use the following syntax:
dataType[] arrayName;
Here, dataType
refers to the type of elements the array will hold, and arrayName
is the name you will assign to the array.
For example, if you want to create an array of integers named numbers
, you would write:
int[] numbers;
To initialize an array, you can either use the new
keyword or directly assign the values.
Here is an example of both methods:
int[] numbers1 = new int[5]; // an array of integers with a length of 5
int[] numbers2 = {1, 2, 3, 4, 5}; // an array of integers initialized with values
Multi-Dimensional Array
Multi-dimensional arrays are arrays of arrays. The elements of a multi-dimensional array are arrays themselves. They can be two-dimensional (2D) or three-dimensional (3D) and so on.
A two-dimensional array is like a table with rows and columns.
To declare a two-dimensional array, you use the following syntax:
dataType[][] arrayName;
Here is an example of a two-dimensional array:
int[][] matrix;
To initialize a two-dimensional array, you can use the new
keyword or directly assign the values.
Here is an example of both methods:
int[][] matrix1 = new int[3][3]; // a 3x3 two-dimensional array
int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // a two-dimensional array initialized with values
Conclusion
Now, you should have a basic understanding of what arrays are in Java, and how to declare and initialize single and multi-dimensional arrays. Practice with these, and in the next topic, we'll dive deep into how to manipulate data within these arrays. Stay tuned!