In this tutorial we will discuss about the array in java and what its need. Suppose a class contain 50 students, and we want to store their roll numbers, we need 50 separate variables for storing the roll numbers, as shown here:

int rno;
int rno1;
int rno2;
.
.
.
int rno49

Now to store roll numbers into these variables, we need another 50 students. Imagine writing 100 statements just to store the roll numbers of students. On other hand, if we have a single variable which can represent all these 50 variables, it would be very useful to us. Such a variable is called an ‘array’.

An array represents a group of elements of same data type. It can store a group of elements. So we can store group of int values or group of float values or group of strings in the array. But we can not store some int values and some float values in the array.

Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values in memory at the fixed size. Multiple types of arrays are used in any programming language such as:
one – dimensional,
two – dimensional or can say multi – dimensional.

In java, array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed elements in an array.

Array is index based, first element of the array is stored at 0 index.

Advantage of Array

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.

Disadvantage of Array

Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in java.

Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:

dataType[] arrayVar;   // preferred way.

or

dataType arrayVar[];  //  works but not preferred way.

Note: The style dataType[] arrayVar is preferred. The style dataType arrayVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:
The following code snippets are examples of this syntax:

int[] myList;         // preferred way.

or

int myList[];         //  works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayVar = new dataType[arraySize];

The above statement does two things:

  • It creates an array using new dataType[arraySize];
  • It assigns the reference of the newly created array to the variable arrayVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below:

dataType[] arrayVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayVar = {value0, value1, ..., valuek};


Example:

Following statement declares an array variable, myList, creates an array of 5 elements of double type, and assigns its reference to myList.:

int[] myList = new int[5];

In java arrays are objects. All methods of an Object can be invoked on an array. Arrays are stored in heap memory.

Though you view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the ‘components’ of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // Summing all elements
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // Finding the largest element
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}

This would produce following result:

output:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example:

The following code displays all the elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}

This would produce following result:

output:
1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}

You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method: 
A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}

The Arrays Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

SN Methods with Description
1 public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1).
2 public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
3 public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other premitive data types ( Byte, short, Int etc.)
4 public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other premitive data types ( Byte, short, Int etc.)

Multidimensional array:
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java:

dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[]; 

Example to initantiate Multidimensional Array in java

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional java array

Let’s see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

class B{
public static void main(String args[]){

//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//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();
}
}
}

output:
   1 2 3
   2 4 5
   4 4 5

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago