- 2
Can someone explain arrays in java to me?
I still don't quite understand how arrays work.
2 Respostas
+ 2
They store values of the same datatype.
{1,2,3,4,4,5,6,7,8,9} for example.
For more info link to here:
https://www.sololearn.com/Course/Java/?ref=app
+ 1
An array is a collection of elements of the same data type (String, integers, float, etc).
Example Array of 5 integers:
elements [1, 2, 3, 4, 5]
indexes 0 1 2 3 4
As you can see, the array are zero based - the indexes start from zero.
So, the first element is at index of 0. And the last element is at index of size of the array (elements count) - 1.
How it works:
Assume you want to get the third element:
int index = 2; // (element position - 1)
int[] array = {1, 2, 3, 4, 5};
System.out.println(array[index]);
// Output: 3
You can print all elements by using loops.
int arraySize = array.length; // (elements count)
for (int i = 0; i <= arraySize; i++) {
System.out.print(array[i] + " ");
}
// Output: ArrayIndexOutOfBound Error
The error is because the loops iterates to the arraySize (5), but the last index = (elements count - 1) = 4.
So, we can fix it on this line:
int arraySize = array.length - 1;
Or in the loop:
for (int i = 0; i < arraySize; i++) {
System.out.print(array[i] + " ");
}
Example using for-each loop:
for (int num: array) {
System.out.print(num + " ");
}
You can modify the elements in many ways, but you can't delete them, or change their data type.
array[2] = -3; // [1, 2, -3, 4, 5]
// Get the max sum of the elements
// It must be 9, since 4 + 5 = 9
int[] arr = {2, 5, 3, 1, 4};
int maxSum = 0;
int sum = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
sum = arr[i] + arr[j];
if (sum > maxSum) {
maxSum = sum;
}
}
}
System.out.println("max sum = " + maxSum);