Unit 6: Arrays
This unit covers array creation, manipulation, and common array algorithms in Java programming.
Key Concepts
- Array Declaration: Creating and initializing arrays
- Array Access: Reading and writing array elements
- Array Traversal: Iterating through arrays
- Array Algorithms: Searching and sorting
- Array as Parameters: Passing arrays to methods
- Array Length: Working with array size
- Array Bounds: Understanding array indices
Classical vs Enhanced For Loops
Feature | Classical For Loop | Enhanced For Loop |
---|---|---|
Syntax | for (int i = 0; i < array.length; i++) |
for (int element : array) |
Index Access | Direct access to index (i) | No direct index access |
Element Modification | Can modify elements | Cannot modify elements |
Reverse Traversal | Possible | Not possible |
Use Cases | When index needed or reverse traversal required | When only reading elements sequentially |
// Example: Classical vs Enhanced For Loops
public class LoopComparison {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Classical for loop
System.out.println("Classical for loop:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
numbers[i] *= 2; // Can modify elements
}
// Enhanced for loop
System.out.println("\nEnhanced for loop:");
for (int num : numbers) {
System.out.println(num);
// num *= 2; // This won't modify the array
}
}
}
Example Code
// Example: Working with Arrays in Java
public class ArrayExamples {
public static void main(String[] args) {
// Array declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
// Array traversal
System.out.println("Numbers array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
// Enhanced for loop
System.out.println("\nNames array:");
for (String name : names) {
System.out.println(name);
}
// Array as parameter
int sum = calculateSum(numbers);
System.out.println("\nSum of numbers: " + sum);
// Array algorithms
int max = findMax(numbers);
System.out.println("Maximum value: " + max);
// Array bounds
try {
System.out.println("Accessing index 5: " + numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds");
}
}
// Method with array parameter
public static int calculateSum(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
// Finding maximum value
public static int findMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
Arrays
Array Basics:
Operation | Description | Example |
---|---|---|
Declaration | Creating an array | int[] numbers = new int[5]; |
Initialization | Setting initial values | int[] numbers = {1, 2, 3, 4, 5}; |
Access | Getting/setting elements | numbers[0] = 10; |
Length | Getting array size | numbers.length |
Array Example:
public class ArrayExample {
public static void main(String[] args) {
// Create and initialize array
int[] numbers = {1, 2, 3, 4, 5};
// Access and modify elements
numbers[0] = 10;
System.out.println("First element: " + numbers[0]);
// Print all elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element " + i + ": " + numbers[i]);
}
// Enhanced for loop
for (int num : numbers) {
System.out.println("Number: " + num);
}
// Array operations
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum);
}
}
Array Operations:
// Finding maximum value
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
// Finding minimum value
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
// Reversing array
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
// Searching for value
boolean found = false;
int target = 5;
for (int num : numbers) {
if (num == target) {
found = true;
break;
}
}
Array Tips:
- Arrays have fixed size after creation
- Index starts at 0 and ends at length-1
- Use length property instead of hardcoded values
- Be careful with array bounds
- Consider using enhanced for loop when possible
Common Pitfalls and Debugging Tips
Common Mistakes:
- Array Index Out of Bounds: Accessing invalid indices
int[] arr = new int[5]; System.out.println(arr[5]); // Wrong! Index 5 is out of bounds System.out.println(arr[4]); // Correct! Last valid index is 4
- Array Initialization: Forgetting to initialize elements
int[] arr = new int[5]; // Wrong! Elements are 0 int[] arr = {1, 2, 3, 4, 5}; // Correct! Initialize with values
- Array Length: Using wrong length
for (int i = 0; i <= arr.length; i++) { // Wrong! Off by one for (int i = 0; i < arr.length; i++) { // Correct! Proper bounds
Debugging Tips:
- Print array contents using Arrays.toString()
- Check array bounds before access
- Verify array initialization
- Use breakpoints to inspect array state
- Test with different array sizes
AP Exam Tips:
- Know array declaration and initialization
- Understand array traversal methods
- Be able to perform basic array operations
- Know how to handle array bounds
- Understand array algorithms
AP Exam-Style Practice Problems
Problem 1: Array Initialization
Consider the following code segment:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i * 2;
}
System.out.println(arr[3]);
What is printed as a result of executing the code segment?
The correct answer is A. The array is initialized with values 0, 2, 4, 6, 8, so arr[3] is 6.
Problem 2: Array Traversal
Consider the following code segment:
int[] arr = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < arr.length; i += 2) {
sum += arr[i];
}
System.out.println(sum);
What is printed as a result of executing the code segment?
The correct answer is A. The loop adds elements at indices 0, 2, and 4 (1 + 3 + 5 = 9).
Problem 3: Array Operations
Consider the following code segment:
int[] arr = {5, 3, 8, 1, 4};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println(max);
What is printed as a result of executing the code segment?
The correct answer is A. The code finds the maximum value in the array, which is 8.
Practice Problems
- Write a program that reverses an array without using a second array.
- Implement a method that finds the second largest element in an array.
- Create a program that removes duplicates from a sorted array.
- Write a method that checks if an array is palindrome (reads same forwards and backwards).
- Implement a method that rotates an array by k positions to the right.
Tips for Success
- Remember that array indices start at 0.
- Always check array bounds before accessing elements.
- Use array.length to get array size.
- Practice common array algorithms like searching and sorting.
- Be careful when modifying array elements in loops.
Interactive Code Playground
Try out your own array code here!
Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.
For actual code execution, we recommend using: