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};
The index number of an array element can be used to access it.
In cars, this statement retrieves the value of the first element:
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.
To modify an individual element’s value, consult the index number:
cars[0] = "Opel";
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Use the length property to determine an array’s element count:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.