To create an array of integers in Java, you can use the new
operator to allocate an array object and assign it to a variable.
Here is an example of how you can create an array of integers in Java:
refet ro:lautturi.comint[] array = new int[5];
This code creates an array of integers with a length of 5 and assigns it to a variable called array
. The array is initialized with the default value of 0 for each element.
You can also use the new
operator to create an array of integers and initialize it with a set of values using an array initializer.
Here is an example of how you can create and initialize an array of integers in Java using an array initializer:
int[] array = {1, 2, 3, 4, 5};
This code creates an array of integers with a length of 5 and assigns it to a variable called array
. The array is initialized with the values 1, 2, 3, 4, and 5 for each element.
You can also use the new
operator to create an array of integers and initialize it with a set of values using a loop.
Here is an example of how you can create and initialize an array of integers in Java using a loop:
int[] array = new int[5]; for (int i = 0; i < array.length; i++) { array[i] = i + 1; }
This code creates an array of integers with a length of 5 and assigns it to a variable called array
. It then uses a for
loop to initialize each element of the array with a value. The value of each element is calculated as the index of the element plus 1.
Once you have created an array of integers, you can access and modify the elements of the array using the array index. The index of an element in an array starts at 0 and goes up to the length of the array minus 1.
Here is an example of how you can access and modify the elements of an array of integers in Java:
int[] array = {1, 2, 3, 4, 5}; // Access the first element of the array int first = array[0]; // Modify the second element of the array array[1] = 10; // Access the third element of the array int third = array[2];
This code creates an array of integers with a length of 5 and assigns it to a variable called array
. It then accesses the first and third elements of the array using the array index and assigns them to variables called first
and third
. It also modifies the second element of the array using the array index.