This tutorial is intended for beginner/intermediate java programmers, who want understand everything about Arrays in Java in easy manner with examples. After you finish this tutorial you will not only gain practical knowledge on Arrays in Java, but also solve coding problems during interview 😎
Goal(s) of this tutorial..
- Familiarize you with Arrays in Java with examples and coding exercises
- Make you feel confident to solve a given Array problem during coding interviews
- Give you satisfaction of learning something new!
But first, Why should you learn Arrays in Java?
- Crucial for interviews. Literally there is no Java interview without Arrays.
- Good understanding of Arrays is an absolute must, for day to day programming.
Before you proceed, make sure you have..
- Some knowledge on Java Programming (If you know how to write a “Hello World” program, you are good to go!)
- Willingness to go though this tutorial completely without distractions
Course Recommendation :
[the_ad id=”2285″]
Here is the summery of content we will cover in this tutorial..
This tutorial on Arrays in Java will cover the following topics,
Setup requirements
You just need to have JDK installed. If you are able to run Java programs, you are good to go!
Why did Someone Introduce Arrays in Java? (Need for Arrays!)
Some random dude (Let’s call him ‘Bill’) was given with a task. He was given with a list of employee names with their salaries and was asked to find out their average salary.
Bill is a lazy guy (Like me). So instead of manually calculating the average salary using a calculator, he decided to write a program and get things fast and also to get accurate results.
The program may look something like this..
//List of employees and their salaries int ron = 10000; int ben = 20000; int sundar = 15000; - - int krish = 10000; //Doing the math to find the average salary. Sum of all the salaries div by no of employees int avgSal = (ron + ben + sundar +....+krish) / n
The above program works great, but is it efficient 😟 ? Let’s think about the following..
- In the above program, bill has to manually count the number of employees accurately to get the average. If he get the count wrong, the number would change. If there are 838 employees, bill has to put that exact number in the formula to get the avgSal. Obviously, it’s not practical to not make mistakes
- If a new employee is added, you have to update the formula as well.
- Takes too many lines of code and the formula gets bigger and bigger as we keep adding new employees.
The above points concerned bill and he introduced “Arrays in Java”.
Real World Example of Arrays!
Imagine that you are running a Car transport company. I mean, you take money to ship your customer car to another location.
Lets say you got 10 orders. How are you going ship them?
Approach 1:
You hire 10 drivers give them each car and let them drive to their destinations. But it has the following drawbacks,
- You have to keep track on 10 vehicles and make sure they reach destination (I mean what if driver takes the car and never to see you again?)
- You’d need to bare the fuel expenses of 10 vehicles
- You will have to pay 10 drivers
Approach 2:
You will have a single truck that carries 10 cars and you hire only 1 driver. This will have the following advantages
- It’s easier to track 1 large vehicle than 10 sneaky vehicles
- You will bare fuel cost of only 1 vehicle
- You pay only to 1 driver
Obviously Approach 2 is the best 👍
The truck has 10 car cabins named car[0], car[1], car[2], car[3],..car[9]. Car 1 will be stored in car[0], Car 2 will be stored in car[1], etc.
Now imagine that the truck has a robotic arm that will give you the car that you ask. For example, if you ask for car[0], it will drop car 1. If you ask for car[6], it will drop car 7. This is the concept on Indexing.
Ladies and gentlemen! That’s exactly what is an Array in Java (More or less. We will discuss).
Declaration and Initializing an Array
To declare and initialize a variable, we do
int ron = 10; int ben = 20; int sundar = 10;
The above code will create a 3 memory locations each taking 4 bytes of memory. However, the syntax for declaring an array is different and will create a huge chunk of memory in one go (Like a truck with certain capacity)
Here is how you’d declare and initialize an array,
int[] arrayName = new int[10];
Let’s break it down,
int[] -> Telling java that we want to create an array of integer type
arrayName -> Name of the Array
new int[10] -> Asking JVM to allocate a new memory of capacity 10. Each with size 4 bytes.
The above instruction is like, manufacturing a truck with capacity 10 and each of it can accommodate a vehicle of type Car. Now guess what? We need to insert values in that array (Like we insert cars in to Truck). Here’s how you do it
arrayName[0] = 10000 arrayName[1] = 20000 arrayName[2] = 30000 - - arrayName[n] = 20000
Even better, instead of assigning each element with array index, you can actually add them directly during array declaration and let the Java compiler do the heavy lifting. Like below code.
In this case, you don’t have to give a fixed size to the array. Java compiler will take care of replacing it with relevant code, depending on the number of elements added.
int[] arrayName = {10000, 20000, 15000..., 20000};
Let’s now introduce the code to find the average of all the values. The code may look like this.
//Loop through all the array elements in 'arrayName' and find sum of all the values by adding each other int sum = 0; for(int d : arrayName) sum +=d; //Find the average using the formula. Multiply by 1.0d to make sure the result is of double value double average = 1.0d * sum / arrayName.length; //Print the average System.out.println("Average : "+ average)
The above code has certain advantages over our earlier example that did not use arrays
- We don’t have to count the number of emplyees. ‘array.length’ will do the job
- Adding a new element (employee) in to array doesn’t require you to change the above code
- Improved no of lines of code
Java Arrays : Memory Management
Declaring a primitive variable would result in creation of memory, regardless of initialization. For example the below code will create a memory of 4 bytes (for Int) with a default value as ‘0’ (Even without assigning a value)
int var;
However, when you declare an array(Like below), it doesn’t actually create any memory unless you initialize it with a value (That’s why in Java all arrays are dynamically allocated.). Once you initialize an array however (say with int array) JVM however will automatically initialize the values to zero (for numeric types), false (for boolean), or null (for reference types).
int[] array;
In case of variables, if you have 10 int variables declared, you’re going to have 10 memory locations created. Where as if you create an array ‘int’ of size 10, it will result in creation of a huge chunk of memory with multiple segments, each of size 4 bytes (for int type).
The total size of an array is not certain and is implementation specific. But typically the size includes the number of elements you add to array, the type of the elements that you add, size of array index, etc.
Arrays are Object in Java and just as any other Object in Java, they are stored in Heap Memory. Look at the below code
int[] array = new int[8];
The above code is going to create an array of integers of size 8 and a reference of that array would be returned back. So that we can use the reference to index through this array and get items in it.
Note: Although Array is an Object time it can store both primitive and non-primitive data types.
Java Arrays : Storing Reference Types
As mentioned before, you can also store reference types in an Array. Look at the code below..
Say you have the following class,
class Employee { public int emp_no; public String name; Employee(int emp_no, String name) { this.emp_no = emp_no; this.name = name; } }
and then you have the following class
public class ArrayExample { public static void main (String[] args) { // declares an Array of Employee. Employee[] arr; // allocating memory for 8 objects of type Employee. arr = new Employee[4]; // initialize the first elements of the array arr[0] = new Employee(1,"Bob"); // initialize the second elements of the array arr[1] = new Employee(2,"Sundar"); // so on... arr[2] = new Employee(3,"Shankar"); arr[3] = new Employee(4,"Johnny"); // accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at " + i + " : " + arr[i].emp_no +" "+ arr[i].name); } }
In this case, student objects would be created prior to creation of the array and the array will store references of those student objects. From the above code, ‘arr[i]’ will return the reference of i’th employee.
Popular Exceptions of Arrays
It’s pretty common for programmers to make mistakes and luckily Java will let you know of your mistakes right away with exceptions. Here are some of the popular Array related exceptions that I personally came across during my initial stages of my Software Developer journey
ArrayIndexOutOfBoundsException – This type of error is generated when an array has been accessed with an illegal index. In other words when an array is accessed by a negative index or more than the size of the array.
Look at this code
int[] arrayName = {10000, 20000, 150003, 20000};
Now if you ask for arrayName[3], it would return ‘20000’. But if you do either arrayName[-10] or arrayName[5] will result in ArrayIndexOutOfBoundsException.
When I take coding interviews, a lot of people aren’t careful of how they use array indexing. I ask them to grab a piece of paper and write a program to solve a given problem. Most often their code result in this exception and so I had to reject them.
Note: Sometimes you may see “IndexOutOfBoundsException” this is the parent class of both “ArrayIndexOutOfBoundsException” and “StringIndexOutOfBoundsException”
ArrayStoreException – This type of exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. Example,
int[] array = new int[8];
//Results in Exception
array [0] = "I am a great programmer!";
NegativeArraySizeException – This error is thrown when anyone wants create an array with a negative size.
Arrays as Arguments & Anonymous Arrays
Just as with any object, you can also send Arrays as method arguments. Example code below
//Declaring and initializing an Array int[] salaries = {10000, 20000, 150003, 20000}; //Sending Array as a method argument findMinSalary(salaries); //Method to print the min salary in a given Array of int salaries static void findMinSalary(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) { if(min>arr[i]) min=arr[i]; } System.out.println(min); }
You can actually send an array without even declaring. They are called Anonymous Arrays
For example, you can replace this code,
//Declaring and initializing an Array int[] salaries = {10000, 20000, 150003, 20000}; //Sending Array as a method argument findMinSalary(salaries);
With, this code
//Sending Array as a method argument findMinSalary(new int[] {10000, 20000, 150003, 20000});
Multidimensional Arrays in Java
A Multidimensional Arrays is simple an Array of Array’s. In other words, you create an Array that holds the references of other Arrays.
int[] intArray = new int[10];// 1D Array int[][] intArray = new int[10][10]; //2D Array or matrix int[][][] intArray = new int[10][10][10];//3D Array
The following code illustrates how to use a multidimensional array. You will have a nested for loop as follows
class multiDimArrayExample { public static void main(String args[]) { // declaring and initializing 2D array int arr[][] = { {2,7,9},{3,6,1},{7,4,2} }; // printing 2D array for (int i=0; i< 3 ; i++) { for (int j=0; j < 3 ; j++) System.out.print(arr[i][j] + " "); System.out.println(); } } }
I will be very honest here. I’ve been contributing to software industry since 2007, but I never ever came across with a situation where I need to use a multi dimensional Array.
Popular Methods of Array
Since Array is essentially a Class, it come with few utility methods. Here are some of the popular ones and this examples
Cloning of arrays
You an clone an array by using clone method(see below code) and now ‘cloneArray’ is same as creating a brand new array with the same value. In this case, there are two memory locations created.
int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); //Will result in false as they both reside in two distinct memory locations System.out.println(intArray == cloneArray);
This is little tricky when it comes to a 2d array though (See below). Here, a copy would be created of the array that holds the references of other arrays (sub-arrays). But, no copy would be created for sub arrays.
Both ‘intArray’ and ‘cloneArray’ would point to the references of same sub-arrays.
int intArray[][] = {{1,2,3},{4,5,6}}; int cloneArray[][] = intArray.clone(); //Will print false System.out.println(intArray == cloneArray); // will print true as shallow copy is created // i.e. sub-arrays are shared System.out.println(intArray[0] == cloneArray[0]); System.out.println(intArray[1] == cloneArray[1]);
Diagram that depicts the above scenario.
Print an Array in the form of a String
You can use the Arrays ‘toString’ method to convert an array to String
int[] intArray = { 1, 2, 3, 4, 5 }; String intArrayString = Arrays.toString(intArray); // Trying to print intArray will print weird characters like 'I@a593d0s', that actually reference value System.out.println(intArray); /Trying to print intArrayStringwill print [1, 2, 3, 4, 5] System.out.println(intArrayString);
If you have an array with Reference or Object type, and you try to print the array, then each objects ‘toString’ method would be called and what ever the code that resides in toString method of the object would be executed. If that code doesn’t print anything, you will not see anything on the output.
Create an ArrayList from an Array
Very often, you want to create an ArrayList from an Array. You can do so by calling ‘asList’ method. The following code will help for the same
Integer[] intArray = { 1, 2, 3, 4, 5 }; ArrayList<Integer> intArrayList = new ArrayList<Integer>(Arrays.asList(intArray ));
Compare two Arrays
int[] arr1 = { 1, 2, 3 }; int[] arr2 = { 4, 5, 6 }; System.out.println (Arrays. Equals (arr1 , arr2)); //false Int [] arr3 = {1, 2, 3}; System.out.println (Arrays.equals (arr1 , arr3)); //true
Array Length
Very often when you are asked to solve a given coding problem, you’d need to find out the length of a given array. For that purpose you can use ‘length’ attribute of Array. Look at the code below
String[] nameArray = {
"Ben"
,
"Den"
,
"Pen"
}; //Prints 3 System.out.println(
"Length of the array : "
+ nameArray.length);
Note: If you initialize and array of size 10 but you have added only 5 elements in to that array, the result of array.length would still be ’10’ regardless of number of elements added!
These are some of the methods and attributes of Array class that are popularly used. But, you are not limited to those. You can actually use external libraries to make use of those methods (Ex: Apache Commons Lang library)
Using those libraries you can do things like concatenating arrays, Converting an ArrayList to Array, reversing a given array, etc.
Reverse and Array
int[] intArray = { 1, 2, 3, 4, 5 }; ArrayUtils.reverse(intArray); //Displays [5, 4, 3, 2, 1] System.out.println(Arrays.toString(intArray));
Remove an element of an array
//Removes the first occurrence of the specified element from the specified array. Result ['b', 'a'] ArrayUtils.removeElement(['a', 'b', 'a'], 'a')
Popular Interview Questions on Arrays
Note: Read the question and try your best to answer on your own. If you don’t succeed, look at the answer.
Q: Describe one major drawback of an Arrays?
The size of an Array is fixed and we cannot either decrease or increase it. In some circumstances, we do not know ahead of time how many element we are going to add in to an array.
However, you can add a custom code to create a dynamic Array, or use ‘ArrayList’ instead.
Q: Can you declare an array without size?
If we declare an array without size, it will throw compile time error. The below code gives “array dimension missing” error
int[] arrayName = new int[];
Q: When will we get When will we get ArrayStoreException??
“ArrayStoreException” is a runtime exception and will be thrown when we try to insert an element of incompatible type. For example, you cannot insert String in to an Integer Array.
Q: What is the meaning of anonymous array? Explain with an example?
Anonymous array means array without any reference.
findMinSalary(new int[] {10000, 20000, 150003, 20000});
Q: When ArrayIndexOutOfBoundsException occurs?
It will occur when the program tries to access an invalid index of an array. Index higher than the size of the array or negative index.
Q: How do we search a specific element in an array?
We can use Arrays.binarySearch() method. This method uses binary search algorithm.
Q: Where is the memory allocated for arrays in Java?
Heap memory, as Arrays in Java are objects.
Q: We know that Arrays are objects so why cannot we write strArray.length()?
Arrays are object references. We can use the methods like toString () and hashCode () against Array. Length is a data item of an array and so it is not a method. That’s why we are using strArray.length to retrieve the size.
Array Coding Problems and their solutions
Now, lets try to do some coding tasks using Arrays.
Note : Take time and try to write the program by yourself on a piece of paper. If you cannot figure out the solution, you can take a look at the provided solution.
Problem : Find the missing number in a given integer array?
Example:
Input: arr[] = {1, 2, 4, 6, 5, 7, 8} Output: 3 Explanation: The missing number from 1 to 8 is 3 Input: arr[] = {1, 2, 4, 5} Output: 3 Explanation: The missing number from 1 to 5 is 3
Clue:
- create a variable sum = 1 to which will store the missing number and a counter c = 2.
- Traverse the array from start to end.
- Update the value of sum as sum = sum – array[i] + c and update c as c++.
- print the missing number as sum.
Java Program (Solution):
// Java implementation class ArrayExample { // a represents the Array // n : Number of elements in the array a static int getMissingNumber(int a[], int n) { int total = 1; for (int i = 2; i <= (n + 1); i++) { total += i; total -= a[i - 2]; } return total; } public static void main(String[] args) { int[] arr = { 1, 2, 3, 5 }; System.out.println(getMissingNumber(arr, arr.length)); } }
Problem : You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers.
Example:
Array = {4, 2, 4, 5, 2, 3, 1} and n = 5
The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2.
Clue:
Traverse the array once. While traversing, keep track of count of all the elements in the array using a temporary array ‘count[]’ of size n, when you see an element whose count is already set, print it as duplicate.
Java Program (Solution):
class ArrayRepElement { void printRepeating(int arr[], int size) { int count[] = new int[size]; int i; System.out.println("Repeated elements are : "); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) System.out.print(arr[i] + " "); else count[arr[i]]++; } } public static void main(String[] args) { ArrayRepElement repeat = new ArrayRepElement (); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); } }
Hope you enjoyed learning, I wish you a great future!
Course Recommendation :
If you are learning Java, I highly recommend you to check out this course. One of the best Java courses online..