Home Snippets Projects Donate

Get Snippets For:

   Java    HTML/CSS JavaScript

The Array

Code Description:

Arrays are data structures that sequentially store elements of the same data type. Arrays have a fixed size which cannot be changed after creation. The first element in an array is at index 0. Array elements are accessed with the array's reference variable name followed by the index enclosed with square brackets. Ex: myArray[5] (retrieves the 6th element in the array since it counts from 0).

Array Syntax:

// Has room to store 4 elements
String[] array = new String[4];

Array Syntax with Known Elements:

// Has room for 3 elements which are already initially set
String[] array = {"string1", "string2", "string3"};

Runnable Array List Example Code:

public class Demo {

    public static void main(String[] args) {

	// Create an array that can hold 4 string elements.
	String[] array = new String[4];
		
	// Set the elements. The index of 0 indicates the first element.
	array[0] = "String 1";
	array[1] = "String 2";
	array[2] = "String 3";
	array[3] = "String 4";
		
	// Display the second element in the array (index of 1).
	System.out.println("Second element of the string array: " + array[1]);
		
	// Create a second array with 5 already declared elements. There is no need to set them individually like the first example.
	int[] integerArray = {1, 2, 3, 4, 5};
		
	// Display the second element in the integer array (index of 1).
	System.out.println("Second element of the integer array: " + integerArray[1]);

    }
	
}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Output:

Array Output Image

Important Notes:

Related Links: