unit 6 Flashcards
What is an array in Java?
An object that stores multiple values of the same type.
How do you declare an array?
dataType[] arrayName;
How do you initialize an array with size 5?
new int[5];
How do you initialize an array with specific values?
int[] arr = {1
What is the index of the first element in an array?
0
What is the index of the last element in an array?
array.length - 1
How do you find the length of an array?
arrayName.length
How do you access the 3rd element in an array?
arrayName[2]
Can you change the value of an element in an array?
Yes
What happens if you access an index outside array bounds?
ArrayIndexOutOfBoundsException
How do you traverse an array?
Use a for loop.
Write a basic array traversal loop.
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }
What is an enhanced for loop?
A loop that automatically goes through each element of an array.
Write an enhanced for loop example.
for (int x : arr) { System.out.println(x); }
Can you modify an array element with an enhanced for loop?
No
What is array traversal?
Visiting each element of an array in sequence.
What is a common algorithm when traversing arrays?
Finding maximum
How do you sum elements in an array?
Initialize a sum variable and add each element in a loop.
How do you find the maximum value in an array?
Initialize max to arr[0]
How do you find how many times a value appears in an array?
Use a loop with an if-statement and a counter.
How do you copy an array manually?
Create a new array and copy elements one by one.
What is array aliasing?
Two references pointing to the same array object.
How can array aliasing cause problems?
Changes made through one reference affect the other.
How do you prevent aliasing?
Create a new array and copy each element.