L6 - Arrays Flashcards
What is an array in Java?
An array is a data structure that holds a collection of elements of the same type, indexed sequentially.
What are the key characteristics of arrays?
- Fixed size once created
- Elements are of the same type
- Indexed from 0 to (size - 1)
How do you declare an array in Java?
int[] numbers;
How do you create an array in Java?
numbers = new int[5]; //Creates an array of size 5
int[] numbers = new int[5]; //Declaration + Creation
How do you initialize an array with values?
int[] numbers = {10, 20, 30, 40, 50}
How do you access an array element?
System.out.println(numbers[2]);
What is the starting index of an array in Java?
Arrays in Java start at index 0.
How do you use a for loop to access an array?
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
How do you find the length of an array?
System.out.println(numbers.length);
What happens if you access an invalid index?
Java throws an ArrayIndexOutOfBoundsException.
How are arrays stored in memory?
Arrays in Java are objects, and the variable stores a reference (memory address) to the array.
What happens when you create an array of objects?
The array stores references to objects, but the objects must be created separately. Example:
Person[] people = new Person[3]; // Creates an array of 3 person references
people[0] = new Person(“Alice”); // Assigns an object to index 0
How do you create an array with a size determined at runtime?
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] numbers = new int[size];
How do you declare a 2D array?
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
How do you access an element in a 2D array?
int value = matrix[1][2]; // Row 1, Column 2
How do you iterate over a 2D array using nested loops?
for(int row = 0; row < matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
System.out.print(matrix[row][col] + “ “);
}
System.out.println();
}
What is a ragged array?
A 2D array where rows have different lengths. Example:
int[][] ragged = new int[3][];
ragged[0] = new int[5];
ragged[1] = new int[2];
ragged[2] = new int[7];
How do you use a for-each loop with an array?
for (int num : numbers){
System.out.println(num);
}
How does selection sort work?
It repeatedly selects the smallest element and swaps it to the front.
How do you sort an array using Java’s built-in method?
Arrays.sort(arr);
How do arrays behave when passed to a method?
Arrays are passed by reference, so modifications affect the original array.
How do you return an array from a method
public static int[] createArray(int size){
return new int[size];
}
How do you prevent privacy leaks when returning an array?
Instead of returning the reference, return a copy:
public int[] getArray(){
return Arrays.copyOf(data, data.length);
}
What is an enumerated type in Java?
A custom type with fixed set of values. Example:
enum Day {MONDAY, TUESDAY, WEDNESDAY}
Day today = Day.MONDAY