Introduction to Arrays in Java Programming
- In today’s section, we are going to look at Arrays in Java Programming. You will come to know about arrays. How to work with Arrays? Also, How to declare, create and initialize the Array? Arrays are suitable for a fixed length. We will see some advantages and disadvantages of arrays. We are also going to see how can we write the program and access the array elements. When array gets nested with multi-dimention it get tedious to understand. If you has clear vision about what exactly is going to happen then it will be very easy to work with array.
- Java is a Programming language. Java follows OOP concept. We can say that java is a pure object-oriented language. In today’s world Java is at the position where every IT sector is related to it with direct and indirect ways.Java has many data types. Some of them are primitive and some are non-primitive. Arrays is a powerful and useful concept used in programming. Java gives us data structure, the array, which can store a fixed-size sequential collection homogeneous elements of the same type.
- An array is used to store a collection of data, but it also more useful to think of an array as a collection of variables of the same type. The class java.util.Arrays have some methods. These methods can get applied on the array to get the index of array, length of arrays. We can also compare two arrays to check both given arrays are the same or not. Suppose we need to get values in an array to place a specific value at each index. At each index, we have to put some values.
- For sorting arrays in ascending order we have some methods to apply. This can be done through the sort method. There are also parallel sort methods in java. The sorting of Parallel and large arrays on multiprocessor systems is faster than sequential array. One of the data type is Array. Suppose we have one scenario where you need to store a lot of data of same type. Array is a static data structure to hold multiple values. Like other variables in java, we can also pass arrays in methods.
Code:
class Demo
{
public static void main(String args[])
{
int a[] = {3, 1, 2, 5, 4};
sum(a);
}
public static void sum(int[] a)
{
// getting sum of array values
int total = 0;
for (int i = 0; i < a.length; i++)
total+=a[i];
System.out.println("sum of array values : " + total);
}
}
Output:
How to Declare Array in Java?
Array is nothing but a collection of data. Array is a collection of homogeneous data types. Also, we can say that array is a data structure for storing similar data values. This stores a similar type of data in one variable. Suppose we have students in a class. Each student is having id.
Suppose 100 students are there. Look at below we will declare variable for each.
Int student1 = 1;
Int student2 = 2;
Int student3 = 3;
Int student4 = 4;
.
.
.
Int student5 = 5;
Huh… it’s still ok. But what, if you have 1000 students. It is very tedious and time-consuming to declare variable 1000 times.
So what’s the solution then? Yes, and the answer is Array. Let’s see how can we declare array.
In Array, we can put values in a single variable.
4.8 (7,974 ratings)
View Course
Ex:
int student[] = new int[1000];
We will see it is clearly in the following diagram:
Student[]
Here, in a single variable, we can store no of values we want. Variable is nothing but the reference to the memory location.
If you have seen carefully we declared the array with the new keyword. Generally, we are using a new keyword to create objects. That means in java arrays are objects.
Hey, hold on what? Object. That means there should be a class that already exists to make its object. Yes, we have one superclass for it and that is object class. Array always extends the class object. Arrays always occupy heap memory. Not only Array objects but all the objects in java are getting stored in heap memory. So we have only one reference to all values. By this, we used memory efficiently. Array is a common topic in nearly all languages. Once we understand the core concept of the array then we can easily tackle it.
How to Initialize Arrays in Java Programming?
Now, the next question arises that how can we initialize array. What does this term mean? Initialization is nothing but the process of assigning value to the variable.
There are multiple ways to initialize arrays in java.
The first way is as shown in the above example while declaring the Array.
Ex:
int student[] = new int[1000];
Next thing is we can initialize array while declaring it as follows:
Ex:
int student[] = {1, 2, 3, 4, 5, 6, ….1000};
While working with the array we may get the exception. If you have learned about error handling in java then you must know the exception. Exception is nothing but the error which is known at runtime get handled efficiently. For array, we have Array Index out of bounds exception.
How to Access Array Elements?
Till now we have learned how to declare and initialize the array. Now the time is to move forward. Let’s consider you have array same as above i.e. student array.
Now, we want particular value to access for doing some programming. How to get the value of a particular element in the array.
In Array, we have the concept of index no.
For ex look at the below diagram.
Index no starts with zero(0).
Types of Array in Java (Explain each type with examples)
Before getting into types of array let’s understand some basic concepts.
The elements in the array allocated by new will automatically get initialized by zero (for numeric types), false (for boolean), or null (for reference types). There are default array values in Java Obtaining an array is a two-step process. You need to declare a variable of the array type. And then, you need to allocate the memory for that which will hold the array, using a new keyword, and it will assign it to the array variable. So, we can say that in Java all arrays are dynamically allocated.
There are two types of arrays as follows:
1. Single Dimensional Array
Single dimensional consists of 1D array. It may have a single row or a single column.
We can declare a single dimensional array as below:
Int[] a; OR Int a[]; OR Int []a; OR Int[]a;
But the most preferred way is int[] a; Do remember that we are not declaring the size of the array here. Ex: int[5] a; is not valid in java. At the time of declaration, we are not giving the size of an array.
Now, we will look at the declaration and creation of the array:
Int[] a; //Declaration of the array
a = new int[5] //Creation of array
At the time of array creation providing the size of an array is very important.
We can declare and create an array in a single line as below:
Int[] a = new int[3];
Now let’s look at how to initialize the array. Suppose you have to add some values in an array. Then you will add it to a particular index no. as below:
a[0] = 1; // We are adding 1 at 0th position in array.
a[1] =2;
a[2] =3;
Now you have seen how to initialize array. But what if I gave the index no which does not exist on the array.
Ex:
a[10] = 11; // suppose we had array of 5 only
At this time it throws an ArrayIndexLoutOf BoundException. You cannot add values beyond the size of an array.
Now, We can declare, create and initialize the array in single line as below:
Int[] a = {1,2,3,4,5}; //Declare, create, initialize
Or another method is as follow
Int[] a = new int[] {1,2,3,4,5};
Now, let’s see how can we retrieve elements from a single-dimensional array:
How to Print Values of Array?
We will use for loop here:
Example:
public class Demo2{
public static void main (String args[]){
int[] a = new int[] {1,2,3,4,5};
for(int i=0; i<=a.length-1;i++)
{
System.out.println(a[i]);
}
}
}
Output:
In the above example, we can loop over the array values.
2. Multi-Dimensional Array
The multi-dimensional array consists of 2d and 3d arrays. It has multiple rows and multiple columns. We also called it an Array of Arrays. We can also call it as jagged arrays. Now let’s look at the array declaration. I mean 2-D array declaration. Above we have seen how to declare a one-dimensional array. Now you are going to see the 2-D array. Same as we read a single dimensional array using its length variable within a for-loop, we can read a 2-dimensional array using its length variable within two for-loops. Suppose, length variable of a single-dimensional array gives the total number of values that can be held by a single dimensional array. The length variable of a 2-dimensional array gives the total number of arrays that can be held by a 2-dimensional array.
Multi-dimensional array can say that array of arrays.
Int [][] a; //here we declared array a
Now, same as above what we did with a one-dimensional array. After declaring array we need to create an array. Look at the below example.
a = new int[2][4];
After this, we are going to initialize an array.
We will understand this with the below diagram more clearly.
By the above diagram, we can easily initialize the array elements.
a[0][0] = 10
a[0][1] = 20
a[0][2] = 30<
a[0][3] = 40
Look at the following diagram above values get inside a given position. We can easily initialize the array with row and column.
Now, All the processes like declaration, creation, and initialization can be done in a single line as below. Please look at the below syntax carefully. First, we will see declaration and creation in one line:
int[][] a =new int[2][3];
Now we will see all three process declaring, creating and initializing the array.
int[][] a = {{10,20,30},{100,200,300}};
Look at the following program to be more precise:
Code:
public class MyArray {
public static void main(String[] args)
{
int[][] a = {{10,20,30},{100,200,300}};
System.out.print(a[1][2]);
}
}
Output:
Try the small programs in the array. Manipulate the values. By making hands dirty while programming most of the small things you will understand.
Advantages and Disadvantages of Arrays in Java Programming
Below we will discuss the advantages and disadvantages.
Advantages
- Array can store multiple values in single variable.
- Arrays are fast as compared to primitive data types.
- We can store objects in array.
- Members of the array are stored into consecutive memory locations.
Disadvantages
- Array has fixed size
- We cannot increase or decrease the size of the array at runtime.
- In array, memory wastage can be more.
- We can store similar data type items only
- While adding or removing items in the middle of the array affects the performance of the array.
Arrays in Java are the data structures used to store elements of the homogeneous data type. The advantage with arrays is that the elements in the array can be accessed using its index number. This makes us easy to perform sorting, fetching, searching and other preferred operations on those elements in arrays considerably fast. The array is such a small concept and can cover in small stipulated time. When we are preparing for the exam or an interview at that time make sure you have seen and implemented all the concepts discussed above.
Conclusion – Arrays in Java Programming
Arrays are a core concept in java. In every programming language if you are an expert in handling arrays and string then it will be the best achievement ever. Arrays are very easy to learn. I just need to remember some core concepts. Once you learned it you will never forget array implementation.
Recommended Articles
This is a guide to for Arrays in Java Programming. Here we discuss the Introduction, advantages, and disadvantages of Arrays in Java Programming, sample codes, and output. You can also go through our other suggested articles –