The Best Technical Blog Ever

twitterrss

Arrays in java

An array is a collection of similar type of elements that can be accessed by a numerical index. In array, instead of declaring individual variables, such as student0, student 1, ..., and student 49, you declare one array variable such as student and use student [0], student [1], and ..., student[49] to represent individual elements. That means an array is a way to store many values under the same name. Array index starts at 0. The length of an array is established when the array is created. First element of the array is stored at index 0. Indices start from 0 to arrayVar.length-1. Array elements are stored in contiguous memory location.


Types of Arrays:

Java has two types of arrays.


  • single dimensional arrays
  • multidimensional arrays

java array


1)Single dimensional arrays :

Declaring Array Variables:

Before using an array, you should declare a array variable with the type.


Syntax:
dataType[] arrayRefVar;       or
dataType []arrayRefVar;      or
dataType arrayRefVar[];

Example:
int[] numbers;

Array Instantiation:

You can create an array by using the new operator.


Syntax:
arrayRefVar=new datatype[size];

We can declare, instantiate and initialize the java array together in one statement


dataType[] arrayRefVar = {value0, value1, ..., valuek};
int[] numbers={10,20,30,40};       //declaration, instantiation and initialization


java array reference


Here, 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 numbers. From the right side part, we can understand, "the array size is 4 and numbers[0] contains 10, numbers[1] contains 20, numbers[2] contains 30 and numbers[3] contains 40". We know all the elements in an array are of the same type and also the size of the array. The size of an array can never be changed. So, for accessing array elements, we often use either for loop or foreach loop.


Example using for loop:
java array

Example using foreach loop:

The foreach loop or enhanced for loop enables you to traverse the complete array sequentially without using an index variable.


java array


Passing Array to method:

We can pass the java array to method as the primitive type values. so that we can reuse it.


java array


Returning array from a Method:

A method can return an array. Following example shows the method that returns an array which is the reversal of another array.


java array


2)Multidimensional arrays:

When the elements of an array are themselves arrays, we say, that the array is multidimensional. In multidimensional arrays, data is stored in matrix form (row and column).


Syntax:
dataType[][] arrayVar;       (or)
dataType [][]arrayVar;       (or)
dataType arrayVar[][];

To create/instantiate a multidimensional array, use new keyword and specify the size of both dimensions of the array. For example:


int[][] numbers = new int[3][4];

Each of the pairs of square brackets represents one dimension, so this is a two-dimensional array. To access a element of this two-dimensional array, you must specify two index values, one for each dimension. Above example declares a array variable named numbers to hold an array of arrays of int. It creates a 2 dimensional array of int that has 12 elements arranged in 3 rows and 4 columns. That means, we have an array with 3 elements. These elements are array with 4 elements. Following example shows initialization of two dimensional arrays.


int[][] A = { { 1, 2, 3, 4 }, { 4, 3, 2, 1 }, { 2, 3, 4, 5 } };

We can also use three-dimensional, four-dimensional, and even higher-dimensional arrays, but they are not used very often in practice.


Example1:
java 2D array

Example2:
java 2D array


Class Objects for arrays:

Every array has an associated Class object, shared with all other arrays with the same component type. For array object, an proxy class is created whose name can be obtained by getClass() and getName() method of the object.


Copying Arrays:

In a program, sometimes you need to duplicate an array or a part of an array. In such cases, to copy an array you can use the following three ways.

  1. Use a loop to copy individual elements.
  2. Use the static arraycopy method in the System class.
  3. Use the clone method to copy arrays.

In the first method, you can write a loop to copy every element from the source array. The following example shows the array copy functionality using a for loop:


Example
array copy

In second method, use arraycopy method of java.lang.System class instead of loop. This arraycopy method is used to efficiently copy data from one array to another.


Syntax:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

To copy an array, specify the array to copy from and the array to copy to and the starting position of the source array, the starting position of the destination array, and the number of array elements to copy.


Before using arraycopy method, the target array must have been created with its allocated memory space. After copying the array, target array and source array have the same content but different memory locations.


Example:
array copy

Here, the arraycopy method begins the copy at element number 3 in the source array. Recall that array indices start at 0, so that the copy begins at the array element 's'. It puts the copied elements into the destination array beginning at the first element (element 0) in the destination array. The copy copies 4 elements: 's', 'o', 'f', and 't'.


Array Manipulations:

Java SE provides several methods for performing array manipulations (common tasks, such as comparing, copying, sorting , filling and searching arrays) in the java.util.Arrays class. These methods are overloaded by all primitive types.


Some useful operations provided by methods in the java.util.Arrays class, are:


  • public static int binarySearch(Object[] array1, Object key)- Searching an array for a specific value to get the index at which it is placed .
  • public static boolean equals(long[] a, long[] a2)-Comparing two arrays to determine if they are equal or not.
  • public static void fill(int[] a, int val)- Filling an array to place a specific value at each index.
  • public static void sort(Object[] a)-Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.
  • public static int[] copyOf(int[] a, int newLength)- Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
  • public static int[] copyOfRange(int[] a, int from, int to)- Copies the specified range of the specified array into a new array.

Anonymous array:

An array that have no explicit reference variable(nameless array) is known as anonymous array. To use an array only once, anonymous object is a better way


Syntax:
New dataType[] {value0, value1,..., valuek};

Example:
anonymous array

Advantages of Java Array:

  • It is capable of storing many elements of same type by using only single name.
  • It allows random accessing of elements i.e. any element of the array can be randomly accessed using indexes.
  • We can retrieve or sort the data easily because of optimized code.

Disadvantages of Java Array:

  • We must know in advance that how many elements are to be stored in array. Predetermining the size of the array is a must.
  • We can store only fixed size of elements in the array. So the memory which is allocated to array cannot be increased or reduced at run time.
  • Because of this fixed size, if we allocate more memory than requirement then the memory space will be wasted. So there is a chance of memory wastage or shortage.
  • The elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming process. To delete one element in the array, we need to traverse throughout the array.
Keypoints to remember in java

1. Java is a high level, robust, secured , platform independent and object oriented programming.... more info

Back to Basics:- Java Syntax

In this session, you are going to refresh some basic set of rules(java syntax), defining how a ... more info

Total Visits
Traffic feed status