What is an Array | Array Class Java | Array in Java
We are going to learn everything about Arrays here, about Array class Java, how to initialize an array in Java, how to use it in methods, and then some of the popular methods.
Working with arrays is fun if you know what you are doing. I had a hard time playing with it, I still remember. There are people who still have array nightmares even though they have learnt a great deal about it and have moved on to become experts.
It’s tricky yes, I will give you that. But there is nothing in this world that is so hard to get that a good thorough reading/learning wouldn’t tackle.
Hopefully, with this chapter trying to clear what array is all about and how to work with it, you and I are both going to become comfortable around the topic.
What is an Array?
This brings us to the question that was playing on your mind all along. What is it?
An array is nothing but a container object that holds similar data types in contiguous memory blocks. These blocks are known as elements, and each element is identified by index numbers.
Remember an array always starts with the index 0.
Here’s the syntax to declare an array in Java:
datatype [] variable; or datatype variable [];
The second one is not the preferred way nowadays. So use the first.
But this isn’t enough though. We need to specify how many blocks we need. That’s where initialization comes into picture.
How to Initialize an Array in Java
In order to initialize the above-declared array, we just need to add the following:
variable = new datatype[n];
where n would be the no. of elements you wish to have in your array.
Notice declaring and initializing the array is the same, the way we used to declare and initialize objects with new operator.
That being said, we can declare and initialize an array it in a single line too just as we could do it for objects.
datatype [] variable = new variable[n];
We will take a look at an example on how to initialize an array in Java:
I have declared an array on the variable ‘b’ with data type as int. I have initialized it by assigning 10 elements in total. To refer to an element we can make use of b[n] code where we just have to replace the code with 0 to 9 indices.
So, I have initialized 4 of the beginning ones leaving the others uninitialized. I am trying to print b[4] as well to see if not initializing an element will assign 0 to it.
I can, of course, declare and initialize an array in the same line:
Here’s the result I will get if I try to run the aforementioned program:
4 67 53 25 0
Notice how 0 is automatically assigned to all the initialized elements of an array.
Alternate Way to Initialize an Array
When there are lesser elements to work with you can alternatively use braces to initialize an array as well. With parenthesis to the rescue you don’t need to use new keyword anywhere.
For example, if there are just 5 elements entailed and you know what values to allot to them, you can simply use:
int []b = {4, 67, 53, 25, 0};
If we put this in our programming code above, things might look like this:
Doing so not only gets rid of some extra coding, but it also saves you a lot of time. You don’t have to even specifically specify how many elements you require. It is understood by the no. of elements you use inside the parenthesis.
The above will also get you the same result if you run it:
4 67 53 25 0
I had earlier mentioned one good example of using a foreach or enhanced for loop to display elements in an array. Do check it out.
How to Check the Length of an Array
Yes, in cases where you are dealing with huge no. of elements in an array, and you are planning on counting them, do not do so manually. It will take you a lot of time, plus it would be stupid when there’s an easier method available. In order to check the
In order to check the length of an array use the following syntax:
array.length;
Now using it to display the length of the array we have been using so far in our program:
If you run the above program you will get the following result:
5
Passing Array to a Method in Java
You can pass array to a method or a constructor as well in Java. Just like you used to pass any primitive or non-primitive data type inside parameters, simply mention it there, and call the method passing array as an argument.
Here is the simplest example to do that:
Running the above program will give you the third element in question:
Thor
Here’s another example:
The result of the above method will be:
4 5 6 6 3 7 8
Now that I have passed a String array as a parameter in a method, why don’t you go ahead and pass an array as a parameter in a Constructor?
Let that be our secret exercise.
How to Return an Array in Java from a Method
Just as it is possible to pass an array as a method, it is possible to expect it to be returned from a method too. Since an array can be used as a return type, all those places where you have been using primitive data types can be replaced with this badass return type.
Here’s an example of a program where you can return an array from a method:
Of course running the above program wouldn’t give you any result, but it simply ensures you can use it as a return type and use the return keyword to grab the output in the form of array.
I think I kind of copied the array into a new array. We have a much better alternative called ArrayCopy method to do that which we will see last in this chapter.
MultiDimensional Array
Up until now, we had been looking at a single dimensional array. Time to enter the multidimensional enclave.
Why do we use a multidimensional array?
You see multidimensional array is useful when you have several choices that are independent of each other. Also, in situations when you are supposed to put arrays inside an array, that’s where using a multidimensional array proves fruitful too. Then in cases where there are reading pixels involved, which is done on a more than one dimension grid of x,y,z, multidimensional arrays come to the rescue.
So basically when your scenario encounters more than 2 dimensions, that’s when you should be steering towards it.
Coders prefer using multidimensional arrays because they are:
- easier to debug
- easier to understand
Here’s the syntax to remember in order to declare and instantiate a multidimensional array:
datatype [][] variable = new datatype[n][];
NOTE: When working with Multidimensional arrays you need to simply specify the memory for the leftmost dimension. That’s why I have put ‘n’ there as a sign so you will remember.
Example to Output Result in a Multidimensional Array
An example to use multidimensional array would be: Let’s assume there are 3 minions who love 3 fruits. And none of them can part with either one of it. How do we divide the array of 3 minions and fruits into a multidimensional setup?
Let’s take this example forward and try to create a multidimensional array:
I have created two separate arrays first instantiating our respective hosts and their fruits. Buttom is not a fruit, but they insisted.
So, then I put a scenario to concatenate both the arrays into a multidimensional (more like a two-dimensional one) and displayed them as is. So each of the minion is getting the fruit that appears to be like their surname.
The result would be something like this:
StuartBanana StuartBable StuartButtom BobBanana BobBable BobButtom KevinBanana KevinBable KevinButtom
Everyone is happy!
Searching for the Class Name of an Array
In Java, as mentioned earlier, Array is a container object. When you instantiate an array a proxy class is created. For cases wherein you are supposed to grab hold of the name of the Class name of the array you can easily do so using the following syntax:
arrayVariable.getClass().getName();
For example, let’s say your array variable goes by the name “array”:
int[] array = {4, 6, 7};
Then your code to obtain Class Name would be:
String name = array.getClass().getName();
Display the name String by using a System.out.println(name) code and voila!
Okay I executed the code I got this weird ClassName:
[I
Don’t worry this is how you will mostly get the result.
Array of Objects
Since we have been using primitive data types to declare Arrays, you must have at one point wondered, is it possible to use reference variables to declare an array?
The answer to that is Yes.
To create an array of objects you need to simply replace the return type of the syntax with the ClassName. So the syntax would become:
ClassName[] arrayVariable = new ClassName[n];
Also, it wouldn’t be enough. Doing so will create arrayVariable[0], arrayVariable[1], arrayVariable[2] and so on, as array of objects. You need to initialize and instantiate these objects as well by using:
new ClassName();
We will create an array of objects and things are as we expect them to be.
Check out the main method wherein I have worked as per the syntax we had established earlier. Calling a method takes an object, an initialized instantiated object and hence im[0], im[1] and im[2] have been initialized and instantiated first before calling the method.
Time has come to finally explore some of the great methods of Array class Java that come in handy. We will delve in to check such methods one by one, but first there is an arraycopy method I wanted to tell you about.
How to Copy an Array from one Array to Another (Using arraycopy method)
There’s a predefined method in the System class that lets you copy one array to another. The syntax of the arraycopy method is:
public static void arraycopy( Object src, int srcPos, Object dest, int destPos, int length) { }
The Object arguments src and dest, are basically talking about the array to be copied from and the array to be copied into. The remaining int elements wish to know what should be the starting position in source and destination, and the number of elements that need copying.
We will put this in the form of an example, and let the enlightenment shower:
When you run the above program you will get the following result:
4 5 7 8
Hey! Hey! Now why do I have to write a for loop in order to display the result inside the new array? If I would have simply tried to print loki it would have given me the following result:
[I@15db9742
Is there a better way?
How to Print Array Elements in Single Line (Using toString Method) : Array Class Java
Yes, there is. In the Array Class Java, there is a method known as toString(array) that saves you the trouble of mentioning a for loop everytime. The best part is that it will print everything you wish to see in an Array format.
You must import Arrays Class before proceeding:
import java.util.Arrays;
Then in the above code, get rid of the for loop, and simply make a minor change:
System.out.println(Arrays.toString(loki));
The code will appear something like this:
Time to run the program. Click on the green button to run it:
Notice the array format? Isn’t that the dream?
In case if you are using a nested array scenario (multidimensional), you can make use of
Arrays.deepToString(array);
to get the result in an array format.
I will leave you to try it as an exercise.
A Better Way to Copy Array (Using copyOfRange Method)
We tried copying an array to another using arraycopy earlier but did you know there was an even better method to do it? We are talking about using copyOfRange method here, and that too is a part of Array Class Java.
The best thing is that it comes as part and parcel of Array Class Java. So you don’t have to scour System class for this method. Plus there are only three arguments here.
The syntax to remember here is:
copyOfRange (int [] original, int from , int to) { }
Of course, I have used int [] here which can be replaced with any data type of your choice whichever you are working on.
Our code will become something like this:
Trying to run the program will get you the same result:
[4, 5, 7, 8]
How to Sort an Array (Using Sort Method)
Another great method of an Array Class Java is the sort method. Sorting an array is a piece of cake. The following method comes in handy:
public static void sort(int [] array) { }
If there is only a part of array that needs to be ordered you can append arguments with fromIndex and toIndex.
Here is an example of sorting an array:
When you try to run the program this is what you will get:
[3, 4, 4, 5, 7, 8, 8, 9]
Now what if you wish to sort it in descending order?
You can make use of a static method of Collections named reverseOrder(). You can pass it as a second parameter to the Arrays.sort() method. The first parameter would be your array. Here’s an example:
Integer b[] = {10,7,8,9,4,6}; Arrays.sort(b,Collections.reverseOrder()); System.out.println(Arrays.toString(b));
If you run the above program you will get this:
[10, 9, 8, 7, 6, 4]
How to Search a Number in an Array (Using binarySearch Method)
Searching for something in a pile of farrago is a challenge. There is a method in Array Class Java that lets you search for a number in an array with maximum ease.
NOTE: Remember in order to search a number using binarySearch method your array must be sorted using sort method.
The syntax to do the binarySearch is:
public static int binarySearch (int [] array, int key) { }
where the key is what you are looking for.
Hey! You know what? I am looking for 7 in my code and I am gonna use this Array Class Java to get what I want.
Let’s see if I can find it:
The answer to the above is displayed as:
Location of 7 in the Array is 4
Correct!
How to Fill an Array with Desired Value (Using Fill method)
Filling a copy with your stuff might have been sometimes a part of your requirement. Don’t worry Array Class Java has got you covered. At times you might be asked to populate your array with a certain value. That’s where fill method of the Array Class Java comes to the rescue.
At times you might be asked to populate your array with a certain value. That’s where fill method of the Array Class Java comes to the rescue.
Here’s the syntax of Fill that comes straigh from the Array class Java.
public static void fill (int [] array, int value) { }
You can alternatively opt for the following syntax if you need to specify fromIndex and toIndex to fill the values into:
public static void fill (int [] array, int fromIndex, int toIndex, int value) {
}
Let’s make the first three values in our example as 1:
The result you will get here is:
[1, 1, 1, 8, 9, 3, 8, 4]
Our job here is done.
The Final Verdict
There are many methods available in the Array Class Java that you can explore.
Remember an array is the best. The only problem with it is that that its size is limited. It doesn’t increase its span on runtime. To overcome that issue we make use of Collection framework in Java which we are going to see in the long run.
I am really tired peeps! Yaaaaaaaaaaaaaaaaa…………..That’s me yawning.
I am gonna sleep now.