Juliet C. answered 09/20/23
Multiple semesters of teaching Java programming courses
Declaring a Java array: Like any other variable, the type of the variable is specified before the name of the variable. For example, an integer variable named num would be declared as
What is the type for an array? It is the type of the elements, followed by square brackets. For example, an array of floating-point numbers named averages would be declared as
Creating a Java array: An array is an object and creating an object involves using the new keyword. For example, creating a Scanner object looks like this
However, for an array, special syntax is used. The element type is used after the new keyword and instead of the normal parentheses for calling a constructor, square brackets are used and an integer number is expected between the square brackets to indicate how many elements the array needs to have. For example, creating an array of 10 floating-point numbers would be done like this
Declaring and creating can be done in the same line of code. For the example of an array of floating-point numbers, this would look like this:
Initializing a Java array: Java automatically initializes an array's elements to 0 (or a value equivalent to 0 for the array's element type). If you want to initialize each element to something other than 0, you need to use a for loop which has an index variable that goes from 0 to one less than the length of the array and assigns a value to the array at each index. For the floating-point numbers array example, this could look like this:
Hint for assigning positive even integers: Think about using the index variable as part of the assignment expression. At index 0, you want to assign 2. At index 1, you want to assign 4. At index 499, you want to assign 1000. What arithmetic expression can you use to do this?