Declaring Arrays
Part of the Fundamentals section of Coddy's Java journey — lesson 58 of 73.
An array is a collection of items, and it can contain values of different types, such as numbers, strings, or even other arrays. Arrays are created using square brackets [], and the items inside the array are separated with commas.
Here is an example of how to create an array:
int[] numbers = {1, 2, 3, 4, 5};To check the length of the array, we can use the .length field:
int length = numbers.length;.length is a field, not a method — so it is accessed without parentheses ().
The variable length will hold 5 because there are 5 elements in the array.
Another way to create an array using the new keyword followed by the array type and size:
int[] numbers = new int[5];Creates an array of 5 integers, all initialized to 0
Challenge
EasyCreate an array called shoppingList that contains the following items: bread, eggs, milk, and butter.
Cheat sheet
Arrays are collections of items created using square brackets [] with items separated by commas:
int[] numbers = {1, 2, 3, 4, 5};Check array length using the .length field:
int length = numbers.length;Create arrays with the new keyword:
int[] numbers = new int[5]; // Creates array of 5 integers, all initialized to 0Try it yourself
public class Main {
public static void main(String[] args) {
// Create the shoppingList array here
// Don't change the code below
System.out.println("Shopping List:");
for (int i = 0; i < shoppingList.length; i++) {
System.out.println(shoppingList[i]);
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 411Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed Array3Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else