Declaring and Creating Arrays

Part of: Array

What Is an Array? An array is a fixed-size, ordered collection of values that all share the same data type . Instead of declaring score1, score2, score3, you store every score in one array and refer to each by position. Declaration Syntax In Java you declare an array reference, then create the array object with new: The [] brackets mark the variable as an array type. int[] reads as "array of int". Default Values When you create an array with new, every element gets a default value : - int, double arrays start filled with 0 (or 0.0) - boolean arrays start filled with false - object arrays (like String[]) start filled with null This matters: a freshly created int[5] already holds five zeros before you assign anything. Fixed Size The length of an array is set at creation and cannot change . new int[5] always has exactly five slots. If you need more room, you create a new, larger array and copy the data over. Initializer Lists When you already know the values, an initializer list declares and fills in one step: The size is inferred from the number of values between the braces. Keep these two creation styles in mind: new int[n] for an empty array of a known size, and {...} for known sta

Challenge: Create and Print an Array