Slide05_ArraysInJava
Arrays in Java
Course Information
Course Code: COP 3330Department: Computer ScienceUniversity: University of Central FloridaInstructor: Dr. Bacanli
Basic Review of Arrays
An array is an elementary data structure that allows for the storage of multiple values of the same type. Data structures are collections of related data items. Arrays are particularly useful when a fixed number of related data items must be stored, enabling efficient access and manipulation of the data.
Key Characteristics of Arrays:
Fixed Size: The size of an array is defined at the time of its creation and cannot be altered once initialized. If an array needs to grow or shrink, a new array must be created and data copied over.
Contiguous Memory Allocation: Elements in an array are stored in contiguous memory locations. This allows for faster access via indexing compared to other data structures like linked lists, where elements can be scattered in memory.
Array Example
Example of an Array:c[0] = -6; c[1] = 2341; c[2] = -53; c[3] = 11; c[4] = 22; c[5] = 34; c[6] = 34; c[7] = 78;
Java Array Syntax
Java's array syntax can sometimes be different from that of C or other programming languages. Here are some examples of correct and incorrect statements:
Incorrect Declaration:
int[] arr;
arr = new int[5];
int arr[]; // not preferred
Correct Declaration and Instantiation:
int[] arr = new int[3];
int arr[] = {45, 45, 223, 3424, 434};
Instantiating the Array
Arrays must be instantiated after they are declared. Both declaration and instantiation can be combined. Here are some examples of initialization:Example with a variable:
int number = 4;
int[] arr = new int[number];
Final variable example:
final int NUMBER = 4;
int[] arr = new int[NUMBER];
Both methods are valid and demonstrate flexibility in assigning array sizes.
Common Questions
What happens to elements after declaration?
When an array is declared, each element is initialized to a default value based on the datatype as follows:
Numeric types (int, float, double, etc.) are initialized to 0.
Boolean types are initialized to false.
Object types are initialized to null.
Array Initialization Examples
One-dimensional array:
int[] arr = {4, 5, 6, 7};
Two-dimensional array:
int[][] arr2d = {{2,3}, {4,5}, {6,7}};
Error example:
int[] arr = new int[1];
arr[0] = 4;
arr[1] = 4; // this will cause an ArrayIndexOutOfBoundsException
Traversing a 1D Array
There are several methods to traverse a 1D array:
Enhanced for-loop:
for(int i : arr) {
System.out.println(i);
}
Regular for-loop:
for(int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Two-dimensional Arrays
A 2D array can be conceptualized as a table, while a 3D array can be viewed as a cube. Here’s how to access elements:
Accessing elements example:
arr[2][3]
refers to the 2nd row and 3rd column.
Dimensions of 2D Arrays:
Number of columns:
arr[0].length = 4
Number of rows:
arr.length = 5
Declaration:
int[][] arr = new int[5][4];
Traversing 2D Arrays
For traversing a 2D array, nested loops are utilized:
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
If all rows have the same size, arr[0].length
will be consistent across rows.
Variable Row Size in 2D Array
An example of variable row sizes is:
int[][] arr2d = {{3}, {4, 5}, {4, 5, 6}};
Nested traversal:
for(int i = 0; i < arr2d.length; i++) {
for(int j = 0; j < arr2d[i].length; j++) {
System.out.print(arr2d[i][j] + " ");
}
System.out.println();
}
Built-in Methods for Arrays
Java includes various utility methods for arrays. The following import statement is necessary:
import java.util.Arrays;
Key Methods:
Arrays.sort() - sorts the elements of an array.
Arrays.toString() - converts an array to a string for display, useful for quick debugging.
Arrays.copyOf() - used for copying or truncating an array efficiently.
Arrays.fill() - populates an array with a single value or fills a subarray with specific value.
The Length Attribute
Arrays possess a length attribute that indicates the number of elements they hold. This is crucial for avoiding ArrayIndexOutOfBoundsException
when accessing elements.
Function example:
public static int[] processArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
arr[i] = -1;
}
return arr;
}
Arrays Class
The Arrays class contains several helpful methods for working with arrays.
Key functionalities include:
Printing the array - provides visual output of the array's contents.
Sorting the array - essential for algorithms that require ordered data.
Searching within the array - efficient methods to locate data within the array.
Example of Arrays.sort():
int[] array = {45, 34, 45, 67, 11, 3, 99, -2};
Arrays.sort(array);
for(int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Java sorts numbers in ascending order by default.
Arrays.toString()
Converts an array to a string for display.Example:
int[] array = {45, 56, 11, 23, 44};
String convertedOutput = Arrays.toString(array);
System.out.println(convertedOutput);
Arrays.copyOf()
Used for copying or truncating an array. Requires two arguments: the original array and the new length.Example:
int[] orig = new int[]{1, 2, 3};
int[] copy = Arrays.copyOf(orig, 5);
System.out.println(Arrays.toString(copy));
Note: Empty slots are filled with default values (0 for integers).
Deep Copy vs Shallow Copy
Shallow Copy:
int[] arr = {45, 56};
int[] arr2 = {4, 4};
arr = arr2; // Changes to arr2 will affect arr as both refer to the same memory location.
Deep Copy: A new array is created with duplicated values to ensure data isolation.
Arrays.fill()
Populates an array with a single specified value.Example of filling specific subarrays:
Arrays.fill(ar, 1, 5, 10); // Fills from index 1 to 4 with 10
Arrays.fill(ar, 10); // Fills the entire array with 10
Methods with Arrays
Void methods: These methods do not return a value, but they can modify the original array directly.Return methods: The original array is returned and could potentially be modified during the process.Example:
public static int[] fixAll(int[] arr) {
for(int el : arr) {
el = 5;
}
return arr;
}
Important Notes
Prefer the long form of array operations for modifications to avoid confusion and ensure clarity in code.
Understand the distinctions between shorthand and longhand operations to ensure accurate modifications while working with arrays.