Array Flashcards
It stores a fixed-size sequential collection of elements of the same type.
Array
consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Array
Syntax for declaring an array variable
datatype[] arrayName;
Syntax for creating an array
arrayName= new datatype[arraySize];
What are the two things that the following statement does?
arrayName= new datatype[arraySize]
- It creates an array using new dataType[arraySize].
- It assigns the reference of the newly created array to the variable arrayName.
Syntax for declaring array variable, creating an array, and assigning the reference of the array to the variable in one line
datatype[] arrayName = new datatype[arraySize];
Identify the parts of the following.
char[] letters = new char[41];
char - data type
letters - array name
[41] - array size
What is the highest index of array?
The highest index of array is the array size - 1
What number does the array in Java always start in?
The array in Java always start in zero
What is the value of the array if not initialized?
The array value if not initialized is zero for number/null for the object
The number that is assigned to each element in an array
Subscript
used as an index to pinpoint a specific element within an array
Subscript
Identify the values of the elements.
int[] num = new int[6];
num[1]= 20;
num[4]= 15;
num[3]= num[1] + num[4];
int x= 2;
num[x] = 5;
int y=1;
num[y-1] = 40;
num[4++]=18;
num[1] - 20
num[2] - 5
num[3] - 35
num[4] - 15
num[5] - 18
What would happen?
int[] num = new int[6];
Array IndexOutofBound Error since the highest index of array subscript is 5 only
Can you can read values from the keyboard and store them in an array element?
Yes
This public field contains the number of elements in the array.
length
can be used in looping instead of the actual size of the array
length
Syntax for array initialization
datatype [] arrayName = {v1, v2, v3…..vn}
Java provides a specialized version of the for loop that, in many circumstances, simplifies array processing.
Enhanced for loop
designed to iterate once for every element in an array.
Enhanced for loop
What is the general format of the enhanced for loop?
for (datatype variable: array) {
}
Identify the parts of the enhanced for loop
for (datatype variable: array) {
}
datatype variable - It is a variable declaration. This variable will receive the value of a different array element during each loop iteration. During the first loop iteration, it receives the value of the first element; during the second iteration, it receives the value of the second element, and so on.
array - It is the name of an array on which you wish the loop to operate. The loop will iterate once for every element in the array.
What would the output be?
int[] num = { 12, 56, 78, 90, 92 };
System.out.println(“Enhance For Loop”);
for(int number : num){
System.out.print(number + “ “);
}
Enhance For Loop
12 56 78 90 92