Question:
Declare and initialize an array in Java named numbers
of integer data type, and initialize it with the values 5, 10, 15, 20, and 25.
Write the code that declares and initializes the array, and print all the elements of the array using a for loop.
Answer:
To declare and initialize the array numbers
in Java with the given values, we can follow these steps:
public class Example {
public static void main(String[] args) {
// Step 1: Declare and initialize the array
int[] numbers = {5, 10, 15, 20, 25};
// Step 2: Print all the elements of the array using a for loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Explanation:
numbers
of integer data type. The values 5, 10, 15, 20, and 25 are enclosed in curly braces {}
and separated by commas.numbers
. The loop starts from index 0 and continues until i
is less than the length of the array numbers
. Inside the loop, we use System.out.println(numbers[i])
to print each element of the array on a new line.The expected output of the above code will be:
5
10
15
20
25
Note: The code provided assumes that it is written within a class. If you are using an online compiler or IDE, make sure to wrap the code inside a class definition before running it.