Arrays - Part 1
![]() |
Arrays in Java - part 1 |
Introduction
Data structures enable us to store and manage data in an efficient manner. This will enable us to access and operate on data with ease.
Java offers different data structures to store the data. In this unit, we will study the most widely used data structure i.e., Arrays, and carry out some basic operations on it.
1. Arrays
In Java, an array is an object that is utilized to store the set of data that are of the same data types (String, int, float, etc.) like lists in Python.
In Java, the number of elements that an array can hold is always fixed.
Array Declaration
The declaration syntax of an array is as follows:
Syntax
dataType[] arrayName;
Here,
The dataType indicates the data type of elements that can be held in the array. It may be primitive data types (int, char, etc.) or non-primitive data types (String, etc.)
The [] following the dataType, distinguishes the array from normal variable declarations.
arrayName is the variable name of the array.
The declaration doesn't create an array, but just informs the compiler that variable arrayName is going to be used to hold an array of dataType
We declare an array named arr whose values can be of type int.
Example
class Main {
public static void main(String[] args) {
int[] arr; // declaring an Array
}
}
2. Creating and Initializing an Array
We can initialize, create and declare an array in one statement.
The syntax to create an array by using array literals is as follows:
Syntax
dataType[] arrayName = {value1, value2, value3,.};
Here, value1, value2, and so on are the values to be stored in the array. These values must be of the same data type as dataType
The array literal {value1, value2,.} initializes the array and the reference of this array object is stored in array variable arrayName
Example:
Code
class Main {
public static void main(String[] args) {
int[] arr = {60, 25, 20, 15, 30};
// declaring, creating and initializing in a single statement
}
}
3. Array Element Accessing
Like Python, array indices are also numbered from 0 i.e., the first element of an array is located at index 0, the second element of an array is located at index 1, and so on.
If an array has size n, then the index of the last element of the array will be n - 1
We can retrieve the elements of an array with these index values.
Syntax
arrayName[index];
In this case, the index value should be between 0 and n - 1 while n represents the size of the array.
Code:
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5};
System.out.println(arr[0]);
System.out.println(arr[1]);
System.out.println(arr[4]);
}
}
Output:
12
4
5
Array Index Out Of Bounds Exception
Accessing array elements with a negative index or, the index value greater than or equal to the size of the array throws an error.
Incorrect Code
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5};
System.out.println(arr[5]);
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Main.main(file.java:5)
In the above code, the size of the arr array is 5. So, the index values must lie between 0 and 4. Since index 5 is outside the range, the error is thrown.
4. Printing an Array
The Arrays class provides a method toString(), which can be used to print the array in Java.
Syntax
Arrays.toString(arrayName);
Code:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5};
System.out.println(Arrays.toString(arr));
}
}
Output:
[12, 4, 5, 2, 5]
5. Modifying Array Elements
Like Java arrays are mutable.
Array elements at any index can be changed but of the same data type.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5};
System.out.println("Initial Array: " + Arrays.toString(arr));
arr[0] = 56;
arr[1] = 100;
arr[4] = 21;
System.out.println("After Modifying elements: " + Arrays.toString(arr));
}
}
Output:
Initial Array: [12, 4, 5, 2, 5]
After Modifying elements: [56, 100, 5, 2, 21]
Possible Mistake
Modifying elements in an array with elements of different data types.
Incorrect Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5};
System.out.println(Arrays.toString(arr));
arr[3] = 10.6;
System.out.println(Arrays.toString(arr));
}
}
Output:
file.java:9: error: incompatible types: possible lossy conversion from double to int
arr[3] = 10.6;
^
1 error
In the above code, we are attempting to update the array arr at index 3 with float value. The array arr cannot hold float values since it is declared with int data type. Therefore, the error is raised.
6. Creating an Array using a new Keyword
We can also create the array with the help of new keyword. With this approach, we can create an array of desired length and then assign the values.
The syntax for declaring an array with a new keyword is as follows:
Syntax
dataType[] arrayName = new dataType[size];
Here, size is used to declare the number of elements we wish to hold in an array.
Example:
Code
class Main {
public static void main(String[] args) {
int[] arr; // declaring an array
arr = new int[3]; // memory for 3 integer values is being allocated
}
}
Above code, the command arr = new int[3] is used to allocate memory to store 3 int values.
Once a memory is created for the array, each element in the byte, short, int, or long type of array is assigned a default value of 0.
For double or float type array, the default value is 0.0 is given. For the String array, the default value is null.
Note:
In Java, null is a reserved literal word. It is a default value for all uninitialized non-primitive data types.
Assigning Values
Let us assign the values to the array declared with the new keyword.
Code
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] arr; // declaring an array
arr = new int[3]; // allocating memory for 3 integer values
arr[0] = 56;
arr[1] = 41;
arr[2] = 25;
System.out.println(Arrays.toString(arr));
}
}
Output
[56, 41, 25]
7. Array Length
The length of an array is the number of elements an array can store.
To get the array length in Java, we can use the attribute length.
Syntax
arrayName.length;
Code:
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5, 2, 5, 7};
int lengthOfArr = arr.length;
System.out.println(lengthOfArr);
}
}
Output:
6
8. Iterating Over an Array
We can iterate over an array using loops.
Using for Loop
We can use for loop to access the array elements one by one.
Code
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5};
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
}
}
Output:
12
4
5
In the given code, arr array has 3 elements. Therefore, n = 3.
The for loop will begin execution from i = 0
At i = 0, System.out.println(arr[0]) will display value of 1st element of arr array.
At i = 1, System.out.println(arr[1]) will display value of 2nd element of arr array.
At i = 2, System.out.println(arr[2]) will display value of 3rd element of arr array.
At i = 3, loop test condition will fail.
Using for-each Loop
Java has a for-each loop that may be utilized in order to move through an array.
While traversing using the for-each loop, we will receive the array elements but no index values.
Syntax
for (dataType variableName : arrayName) {
// body of loop
}
Here,
arrayName: the name of an array
variableName: during iteration, every element of the array is given this variable.
dataType: data type of an array
Code
class Main {
public static void main(String[] args) {
int[] arr = {12, 4, 5};
for(int element: arr){
System.out.println(element);
}
}
}
Output:
12
4
5
9. Read & Store User Inputs in an Array
Until now we have read user inputs and stored them in a variable. To read and store the user inputs in an array, first, we have to declare an array of required size.
Suppose the initial input from the user is the desired array length and subsequent inputs are the values that need to be stored in the array.
Code
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt(); // n is how many elements you want to keep in the array
int[] arr = new int[n]; // creating and declaring an array
for (int i = 0; i < n; i{})
arr[i] = input.nextInt(); // reading inputs for array
}
System.out.println(Arrays.toString(arr));
input.close();
}
}
Input:
7
34 45 19 90 2 100 56
Output:
[34, 45, 19, 90, 2, 100, 56]
In the above code, the first number 7 is the array length. The subsequent space separated numbers are the actual values to be stored.
In every iteration of the for loop, the nextInt() method reads a number and stores it in the array.
Summary
In Java, the number of elements that an array can store is always fixed.
While declaring an array by using the keyword new, the default values will be set as per the array data type.
0 is allocated to each component in byte, short, int, or long type array.
0.0 is allocated in the case of double or float type of array.
null is allocated for String array.
ToString() method from the class Arrays can be utilized to display the array.
We can discover the array length in Java using the property length
When we use for-each loop for iteration, we will have array elements but no index values.
Very useful....
ReplyDelete