Java Arrays

As an alternative to declaring distinct variables for each value, arrays can hold many values in a single variable.

Use square brackets to define the variable type in order to declare an array:

				
					String[] cars;
				
			

Now that we have a variable specified, it may hold an array of strings. You can add values to it by putting them inside curly braces as a list separated by commas:

				
					String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
				
			

You could write: in order to generate an array of integers.

				
					int[] myNum = {10, 20, 30, 40};
				
			

Access the Elements of an Array

The index number of an array element can be used to access it.

In cars, this statement retrieves the value of the first element:

Example

				
					String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo
				
			

Recall that array indexes begin at 0: The first element is [0]. The second element is [1], and so on.

Change an Array Element

To modify an individual element’s value, consult the index number:

Example

				
					cars[0] = "Opel";
				
			

Example

				
					String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
				
			

Array Length

Use the length property to determine an array’s element count:

Example

				
					String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
				
			
Share this Doc

Arrays

Or copy link

Explore Topic