Arrays 1D and 2D

Arrays 1D and 2D

Today in this article we will be discussing about Arrays 1D and 2D in java.

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.

Multithreading in Java

Array is a data structure that is used to store variables that are of similar data types at contiguous locations. The main advantage of the array is random access and cache.

 

  • It is a list of the variable of similar data types.
  • It allows random access and all the elements can be accessed with the help of their index.
  • The size of the array is fixed.
  • For a dynamically sized array, vector can be used in C++.
  • Representation of 1D array:
Arrays 1D and 2D

In Java language, int[] numbers; declares an array called numbers. Then, we can allocate memory for that array using ‘new’ keyword as follows.

  • numbers= new int[10];

This array is capable of storing 10 integer values. We can combine the above two statements together and write as follows.

  • int numbers = new int[10];

Below is an example of assigning values to the array.

  • numbers ={1,2,3,4,5,6,7,8,9,10};

The starting index of an array is 0. Therefore, the element in the 0th index is 1. The element in the 1st index is 2. The element in the 2nd index is 3, etc. The index of the final element is 9.

If the programmer wants to store number 50 on the 2nd index, he can write the statement as follows.

  • numbers[2] = 50;

Two Dimensional Array:

  • It is a list of lists of the variable of the same data type.
  • It also allows random access and all the elements can be accessed with the help of their index.
  • It can also be seen as a collection of 1D arrays. It is also known as the Matrix.
  • Its dimension can be increased from 2 to 3 and 4 so on.
  • They all are referred to as a multi-dimension array.
  • The most common multidimensional array is a 2D array.
  • Representation of 2 D array:

For example, int[][] numbers; declares a 2D arrays.

  • numbers = new int [2][3];

 The above statement allocates memory for a 2D array of 2 rows and 3 columns. We can combine the above two statements together and write the statement as follows.

  • int[][] numbers = new int[2][3];

Below is an example of assigning values to the 2D array.

  • int[][] numbers = { {10,20,30}, {50,60,70}};

Similar to a 1D array, the starting index of the 2D array is also 0. This array has two rows and three columns. The indexes of the rows are 0 and 1 while the indexes of columns are 0, 1 and 2. The element 10 is in the 0th row 0th column position. Number 20 is in the 0th row, 1st column position. Number 70 is in 1st row, 2nd column position.

  • numbers[1][2] = 50;

Above statement assigns number 50 to 1st row, 2nd column position.  

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription