What is an array?
An array is basically a container of objects of the same type. The rule of creating an array of objects is basically a must. During creation of an array, it must be declared what type should it hold, and this must be followed strictly without fail otherwise a compilation problem or runtime errors will occur. What I mean to say is, if we declare an array of Integers and we add an element that is of type String? What would happen? It would result to compilation problem.
How to define and instantiate an array in java?
Those objects in an array is called an element. And each element can be called through array index.
The index of an array starts at 0 thus the first element of an array is located at index 0. Moreover the last element is equal to size of an array – 1. This is one of the fundamentals of an array that most programmers get confused on.
There are so much into arrays, that’s why let’s do it by providing an example
Below are some examples and some brief explanation.
From the above code snippet, that how you instantiate array. As you can see we have used an int data type on the left side of the statement and beside it is the opening and closing square bracket which tells the compiler that this is an array of int and the variable name of the array is arrayInt. On the right side of.
// array of Strings of size 2 since values were already declared during initialization
// multi dimensional array of strings. Below is a sample declaration. Basically we have an array with 5 elements. These elements are array with dimension 2.
// example code in instantiating an array of objects
How to access the elements inside an array
From the earlier part of this tutorial, we have already showed examples on how to instantiate an array. We have also tackled multi dimensional arrays. But what would be the use of these arrays? That’s what we gonna tackle on this part.
// access the elements inside the array
// access all the elements inside the array using for loop
// print all contents of a java array using advance for loop (for-each)
How to copy elements of an array to another array
Using the arraycopy() method of System class, we would be able to copy all elements of an array or only specific elements of an array efficiently.
How to replace a specific element of an array
This is very simple scenario we just have to assign a value to the target index
I have also written a compilation of java tutorials on java array examples. This compilation contains source codes for specific scenarios which you can readily modify to suit your needs.