Java Programming
Lecture 07: Arrays - 1D Arrays and Basics
Course: 4343203 - Java Programming
GTU Semester 4 | Unit 2
Learning Objectives:
- Understand array concepts and memory organization
- Master array declaration, initialization, and access
- Learn array traversal and manipulation techniques
- Apply common array algorithms and operations
- Handle array bounds and exception scenarios
Introduction to Arrays
Array is a collection of elements of the same data type stored in contiguous memory locations, accessed using a common name and index.
Key Characteristics:
- Homogeneous: Same data type elements
- Fixed Size: Size determined at creation
- Contiguous Memory: Elements stored sequentially
- Zero-based Indexing: First element at index 0
- Random Access: O(1) access time
Why Use Arrays?
- Store multiple values efficiently
- Fast element access using index
- Implement data structures and algorithms
- Process large datasets systematically
- Memory efficient storage
Array Visualization:
| 10 | 20 | 30 | 40 | 50 |
| [0] | [1] | [2] | [3] | [4] |
Base Address + (Index × Element Size)
Array Declaration and Initialization
Declaration Syntax:
// Method 1: Declare then initialize
dataType[] arrayName;
arrayName = new dataType[size];
// Method 2: Declare and initialize together
dataType[] arrayName = new dataType[size];
// Method 3: Declare with values
dataType[] arrayName = {value1, value2, ...};
// Examples:
int[] numbers; // Declaration only
numbers = new int[5]; // Memory allocation
int[] scores = new int[10]; // Declare and allocate
int[] grades = {85, 90, 78, 92, 88}; // With initial valuesDifferent Data Types:
// Integer arrays
int[] integers = {1, 2, 3, 4, 5};
long[] longNumbers = new long[8];
// Floating-point arrays
double[] prices = {19.99, 25.50, 12.75};
float[] temperatures = new float[7];
// Character arrays
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
char[] letters = new char[26];
// Boolean arrays
boolean[] flags = {true, false, true};
boolean[] results = new boolean[100];
// String arrays
String[] names = {"Alice", "Bob", "Charlie"};
String[] cities = new String[50];Memory Allocation Process:
public class ArrayMemoryDemo {
public static void main(String[] args) {
// Step 1: Reference variable created on stack
int[] numbers;
// Step 2: Array object created on heap
numbers = new int[5]; // All elements initialized to 0
// Step 3: Assign values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Display array information
System.out.println("Array length: " + numbers.length);
System.out.println("First element: " + numbers[0]);
System.out.println("Last element: " + numbers[numbers.length - 1]);
}
}Array Access and Manipulation
Accessing Elements:
int[] scores = {85, 90, 78, 92, 88};
// Reading elements
int firstScore = scores[0]; // 85
int lastScore = scores[4]; // 88
int middleScore = scores[2]; // 78
// Using variables as indices
int index = 3;
int score = scores[index]; // 92
// Array length property
int arraySize = scores.length; // 5
int lastIndex = scores.length - 1; // 4
System.out.println("Array size: " + arraySize);
System.out.println("Last element: " + scores[lastIndex]);Modifying Elements:
// Update individual elements
scores[0] = 95; // Change first element to 95
scores[2] = 80; // Change third element to 80
// Update using loops
for (int i = 0; i < scores.length; i++) {
scores[i] += 5; // Add 5 to each score
}
// Conditional updates
for (int i = 0; i < scores.length; i++) {
if (scores[i] < 80) {
scores[i] = 80; // Minimum score of 80
}
}Array Traversal Methods:
1. Traditional for loop:
int[] numbers = {10, 20, 30, 40, 50};
// Forward traversal
System.out.println("Forward:");
for (int i = 0; i < numbers.length; i++) {
System.out.println("Index " + i + ": " + numbers[i]);
}
// Backward traversal
System.out.println("Backward:");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println("Index " + i + ": " + numbers[i]);
}2. Enhanced for loop:
// Read-only traversal
System.out.println("Enhanced for loop:");
for (int number : numbers) {
System.out.println("Value: " + number);
}
// Cannot modify array using enhanced for loop
// This won't change the original array:
for (int number : numbers) {
number = number * 2; // Only local copy is changed
}3. While loop traversal:
int index = 0;
while (index < numbers.length) {
System.out.println(numbers[index]);
index++;
}Common Array Operations
1. Finding Maximum and Minimum:
public static int findMax(int[] array) {
if (array.length == 0) return Integer.MIN_VALUE;
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
public static int findMin(int[] array) {
if (array.length == 0) return Integer.MAX_VALUE;
int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}2. Sum and Average:
public static int calculateSum(int[] array) {
int sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
public static double calculateAverage(int[] array) {
if (array.length == 0) return 0.0;
int sum = calculateSum(array);
return (double) sum / array.length;
}3. Linear Search:
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Return index if found
}
}
return -1; // Not found
}
// Count occurrences
public static int countOccurrences(int[] array, int target) {
int count = 0;
for (int value : array) {
if (value == target) {
count++;
}
}
return count;
}4. Array Copying:
public static int[] copyArray(int[] original) {
int[] copy = new int[original.length];
for (int i = 0; i < original.length; i++) {
copy[i] = original[i];
}
return copy;
}
// Using System.arraycopy()
public static int[] copyArrayFast(int[] original) {
int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
return copy;
}
// Using Arrays.copyOf()
import java.util.Arrays;
public static int[] copyArrayUtil(int[] original) {
return Arrays.copyOf(original, original.length);
}Array Sorting Algorithms
Bubble Sort Implementation:
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
// Last i elements are already sorted
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap elements
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swapped = true;
}
}
// If no swapping occurred, array is sorted
if (!swapped) break;
}
}
// Usage example
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Before sorting: " + Arrays.toString(numbers));
bubbleSort(numbers);
System.out.println("After sorting: " + Arrays.toString(numbers));Selection Sort Implementation:
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
// Find minimum element in remaining array
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// Swap found minimum with first element
if (minIndex != i) {
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
// Built-in sorting
import java.util.Arrays;
public static void sortArray(int[] array) {
Arrays.sort(array); // Uses optimized quicksort
}
// Sorting in descending order
public static void sortDescending(int[] array) {
Arrays.sort(array);
// Reverse the array
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}| Algorithm | Best Case | Average Case | Worst Case | Space Complexity | Stable |
|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Arrays.sort() | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
Array Bounds and Exception Handling
ArrayIndexOutOfBoundsException:
public class ArrayBoundsDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Valid access
System.out.println(numbers[0]); // OK: 10
System.out.println(numbers[4]); // OK: 50
// Invalid access - Runtime Exception!
try {
System.out.println(numbers[5]); // Error!
System.out.println(numbers[-1]); // Error!
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
System.out.println("Error: " + e.getMessage());
}
}
}Safe Array Access:
public static int safeGet(int[] array, int index) {
if (array == null) {
throw new IllegalArgumentException("Array is null");
}
if (index < 0 || index >= array.length) {
throw new IndexOutOfBoundsException(
"Index " + index + " is out of bounds for array of length " + array.length
);
}
return array[index];
}
public static boolean isValidIndex(int[] array, int index) {
return array != null && index >= 0 && index < array.length;
}Common Pitfalls and Solutions:
1. Off-by-one errors:
int[] array = new int[5]; // Indices: 0, 1, 2, 3, 4
// Wrong: array.length is 5, but max index is 4
for (int i = 0; i <= array.length; i++) { // ❌ Error!
array[i] = i;
}
// Correct:
for (int i = 0; i < array.length; i++) { // ✅ Correct
array[i] = i;
}2. Null array reference:
public static void processArray(int[] array) {
if (array == null) {
System.out.println("Array is null!");
return;
}
if (array.length == 0) {
System.out.println("Array is empty!");
return;
}
// Safe to process array
for (int value : array) {
System.out.println(value);
}
}3. Input validation:
public static void updateElement(int[] array, int index, int value) {
if (array == null) {
throw new IllegalArgumentException("Array cannot be null");
}
if (index < 0 || index >= array.length) {
throw new IndexOutOfBoundsException(
"Index must be between 0 and " + (array.length - 1)
);
}
array[index] = value;
}Previous Year Exam Questions
Q1. (GTU Summer 2022) Write a Java program to find the second largest element in an array without sorting the array.
Solution:
public class SecondLargest {
public static int findSecondLargest(int[] array) {
if (array == null || array.length < 2) {
throw new IllegalArgumentException("Array must have at least 2 elements");
}
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > largest) {
secondLargest = largest; // Update second largest
largest = array[i]; // Update largest
} else if (array[i] > secondLargest && array[i] != largest) {
secondLargest = array[i]; // Update second largest
}
}
if (secondLargest == Integer.MIN_VALUE) {
throw new RuntimeException("No second largest element found (all elements are same)");
}
return secondLargest;
}
public static void main(String[] args) {
// Test cases
int[] test1 = {12, 35, 1, 10, 34, 1};
int[] test2 = {10, 5, 10};
int[] test3 = {1, 1, 1, 1};
System.out.println("Array 1: " + java.util.Arrays.toString(test1));
try {
System.out.println("Second largest: " + findSecondLargest(test1));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("\nArray 2: " + java.util.Arrays.toString(test2));
try {
System.out.println("Second largest: " + findSecondLargest(test2));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("\nArray 3: " + java.util.Arrays.toString(test3));
try {
System.out.println("Second largest: " + findSecondLargest(test3));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// Alternative method with detailed tracking
alternativeMethod(test1);
}
public static void alternativeMethod(int[] array) {
System.out.println("\n=== Alternative Method ===");
System.out.println("Array: " + java.util.Arrays.toString(array));
int first = array[0];
int second = Integer.MIN_VALUE;
for (int i = 1; i < array.length; i++) {
if (array[i] > first) {
second = first;
first = array[i];
System.out.println("New largest: " + first + ", Second: " + second);
} else if (array[i] > second && array[i] != first) {
second = array[i];
System.out.println("New second largest: " + second);
}
}
System.out.println("Final Result - Largest: " + first + ", Second Largest: " + second);
}
}Q2. (GTU Winter 2021) Explain array initialization in Java with examples. Write a program to reverse an array without using additional array.
Solution:
Array Initialization Methods:
1. Declaration and Initialization Separately:
int[] numbers; // Declaration
numbers = new int[5]; // Memory allocation with default values (0)
numbers[0] = 10; // Manual assignment
numbers[1] = 20;2. Declaration and Initialization Together:
int[] numbers = new int[5]; // All elements = 0
double[] prices = new double[3]; // All elements = 0.0
boolean[] flags = new boolean[4]; // All elements = false
String[] names = new String[2]; // All elements = null3. Declaration with Initial Values:
int[] numbers = {10, 20, 30, 40, 50}; // Direct assignment
String[] colors = {"red", "green", "blue"}; // String array
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // Character array4. Using new keyword with values:
int[] numbers = new int[]{10, 20, 30, 40, 50}; // Explicit size
String[] names = new String[]{"Alice", "Bob"}; // Explicit declarationArray Reversal Program:
public class ArrayReversal {
public static void reverseArray(int[] array) {
int start = 0;
int end = array.length - 1;
System.out.println("Original array: " + java.util.Arrays.toString(array));
while (start < end) {
// Swap elements at start and end positions
int temp = array[start];
array[start] = array[end];
array[end] = temp;
// Move pointers towards center
start++;
end--;
// Show progress
System.out.println("Step: " + java.util.Arrays.toString(array));
}
System.out.println("Reversed array: " + java.util.Arrays.toString(array));
}
// Alternative method using for loop
public static void reverseArrayFor(int[] array) {
int n = array.length;
for (int i = 0; i < n / 2; i++) {
// Swap array[i] with array[n-1-i]
int temp = array[i];
array[i] = array[n - 1 - i];
array[n - 1 - i] = temp;
}
}
public static void main(String[] args) {
// Test with different arrays
int[] test1 = {1, 2, 3, 4, 5};
int[] test2 = {10, 20, 30, 40};
int[] test3 = {42}; // Single element
int[] test4 = {}; // Empty array
System.out.println("=== Test 1: Odd length array ===");
reverseArray(test1.clone()); // Use clone to preserve original
System.out.println("\n=== Test 2: Even length array ===");
reverseArray(test2.clone());
System.out.println("\n=== Test 3: Single element ===");
reverseArray(test3.clone());
System.out.println("\n=== Test 4: Empty array ===");
reverseArray(test4.clone());
}
}Q3. (GTU Summer 2020) Write a Java program to search for an element in an array using linear search. Display appropriate message if element is found or not found.
Solution:
import java.util.Scanner;
public class LinearSearchProgram {
// Linear search method
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
// Enhanced search with multiple occurrences
public static void searchAllOccurrences(int[] array, int target) {
boolean found = false;
System.out.print("Element " + target + " found at positions: ");
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
System.out.print(i + " ");
found = true;
}
}
if (!found) {
System.out.print("Not found");
}
System.out.println();
}
// Count occurrences
public static int countOccurrences(int[] array, int target) {
int count = 0;
for (int element : array) {
if (element == target) {
count++;
}
}
return count;
}
public static void main(String[] args) {
// Initialize array with sample data
int[] numbers = {64, 25, 12, 22, 11, 90, 88, 25, 12};
Scanner scanner = new Scanner(System.in);
System.out.println("Array elements: " + java.util.Arrays.toString(numbers));
System.out.print("Enter element to search: ");
int searchElement = scanner.nextInt();
// Perform linear search
int result = linearSearch(numbers, searchElement);
if (result != -1) {
System.out.println("✅ Element " + searchElement + " FOUND at index " + result);
System.out.println("Position: " + (result + 1) + " (1-based indexing)");
} else {
System.out.println("❌ Element " + searchElement + " NOT FOUND in the array");
}
// Additional information
System.out.println("\n=== Additional Information ===");
searchAllOccurrences(numbers, searchElement);
int count = countOccurrences(numbers, searchElement);
if (count > 0) {
System.out.println("Total occurrences: " + count);
}
// Performance analysis
System.out.println("\n=== Performance Analysis ===");
System.out.println("Array size: " + numbers.length);
System.out.println("Search completed in " + (result + 1) + " comparisons");
System.out.println("Time complexity: O(n)");
System.out.println("Space complexity: O(1)");
// Interactive search loop
System.out.println("\n=== Interactive Search ===");
while (true) {
System.out.print("Enter another element to search (or -999 to exit): ");
int element = scanner.nextInt();
if (element == -999) {
break;
}
int index = linearSearch(numbers, element);
if (index != -1) {
System.out.println("Found at index " + index);
} else {
System.out.println("Not found");
}
}
System.out.println("Search program terminated.");
scanner.close();
}
}Hands-on Lab Exercises
Exercise 1: Array Statistics Calculator
- Create a program that takes an array of integers and calculates:
- Sum, average, maximum, minimum values
- Count of positive, negative, and zero elements
- Standard deviation of the elements
- Display results in a formatted table
- Handle edge cases (empty array, single element)
// Template for Exercise 1
public class ArrayStatistics {
public static void calculateStatistics(int[] array) {
// TODO: Implement all statistical calculations
// Display results in formatted output
}
}Exercise 2: Array Manipulation Operations
- Implement the following array operations:
- Insert element at specific position
- Delete element from specific position
- Rotate array left and right
- Merge two sorted arrays
- Create interactive menu to test all operations
Exercise 3: Pattern Detection in Arrays
- Write programs to detect patterns in arrays:
- Check if array is sorted (ascending/descending)
- Find longest increasing subsequence
- Detect duplicate elements and their frequencies
- Find all pairs that sum to a target value
Lecture Summary
Key Concepts Covered:
- Array fundamentals and memory organization
- Declaration, initialization, and access methods
- Array traversal techniques (for, enhanced for, while)
- Common array operations and algorithms
- Sorting algorithms (bubble sort, selection sort)
- Exception handling and bounds checking
- Best practices for array programming
Learning Outcomes Achieved:
- ✅ Understand array memory model and indexing
- ✅ Master array declaration and initialization
- ✅ Implement array traversal and manipulation
- ✅ Apply common array algorithms effectively
- ✅ Handle array exceptions and bounds checking
- ✅ Optimize array operations for performance
- ✅ Debug array-related programming errors
Next Lecture: Arrays - 2D Arrays and Advanced Operations
Topics: Multidimensional arrays, matrix operations, jagged arrays, array of objects
Thank You!
Questions & Discussion
Next: Lecture 08 - Arrays (2D Arrays and Advanced Operations)
Course: 4343203 Java Programming
Unit 2: Arrays and Object-Oriented Programming
GTU Semester 4

