Java Array

Java Array is used to store similar type of data in single variable.

The elements of an array are stored in a contiguous memory location. Array values can be access using index.

Array declare using square [] bracket as shown below.

String[] studentArray;

Below is an example of an array with values. The value “one” will be stored at index 0, followed by “two” at index 1 and so on.

String [] countArr = {"one", "two", "three"};

Below is the pictorial representation of countArr array of length 3. First index item can get access through 0. e.g. countArr[0] will return one.

Access Array values:

In the below code, the countArr array contains multiple values. We can access those values directly by index or loop through them.

1. Using for loop:

2. Using Index:

Below is the example of accessing array elements using index values where “one” exists at the 0 index, “two” exist at the 1st index and “three” exist at the 2nd index.

3. Enhanced For Loop:

We can access above count array with the help of enhanced for loop:

Syntax:

For(arrayDataType variableName : array) {
// Block of Code
}

Example:

Update Array Values:

Below is an example of updating the array value at index 1. The previous value was declared as two in the countArr array and printed as two at line number 7. At line 9, change the value to 2. Line 12 displays the updated value as 2.

Array Length

Array length denotes the total number of items in an array. Array length can be check by .length property.

Multidimensional Array

A multidimensional array contains one or more arrays.

String[][] number= {{1,2,3,4},{5,6,7,8}};

Below is the pictorial representation of above multidimensional array:

Example

Access multidimensional Array using for loop. 

Below is the example of two dimensional array.

Sample Code snippet:

A single-dimensional array uses one for loop to access array elements, a two-dimensional array uses two for loops, and an n-dimensional array uses n for loops.

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan