Array
Lesson 10 of 16 in Coddy's Strings and Arrays in Java course.
Arrays are used to store multiple values in a single variable.
To declare an array, define the variable type with square brackets:
int[] numbers;Just like a string, an array is also a non-primitive type.
To initialize the array values, place the values in a comma-separated list, inside curly braces:
int[] numbers = {1, 5, 12, 435};The same goes for any type, for example, a String one:
String[] names = {"Bob", "Alice", "John"};To get the length of an array, use the length property:
System.out.println(names.length); // Outputs 3Notice that here
lengthis a property and not a method, like inString.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou are given a code, your tasks are:
- Declare and initialize an array (of type
double) namedcoolNumswith the values: 3.14, 1.68, 9.99 (in this order!) - Print the length of the array you declared.
Try it yourself
class Main {
public static void main(String[] args) {
// Write code here
// Don't change below this line
System.out.print(coolNums[0]);
System.out.print(", ");
System.out.print(coolNums[1]);
System.out.print(", ");
System.out.print(coolNums[2]);
}
}