Java Arrays Reviewer
1. What is an Array?
An array is a container object that holds a fixed number of values of a single data type. Each item in an array
is called an element, and each element is accessed by its index.
2. Declaring Arrays
int[] numbers; // Preferred way
String names[]; // Also valid
3. Creating Arrays
int[] numbers = new int[5]; // Creates an array of 5 integers
String[] names = new String[3]; // Creates an array of 3 strings
4. Initializing Arrays
int[] scores = {90, 85, 70, 100}; // Inline initialization
scores[0] = 95; // Assigning values by index
5. Accessing Array Elements
System.out.println(scores[2]); // Outputs: 70
6. Array Length
int length = scores.length; // Get number of elements in the array
7. Looping Through Arrays
Using a for loop:
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
Java Arrays Reviewer
Using a for-each loop:
for (int score : scores) {
System.out.println(score);
8. Multidimensional Arrays
int[][] matrix = {
{1, 2},
{3, 4},
{5, 6}
};
System.out.println(matrix[1][1]); // Outputs: 4
9. Common Array Operations
- Sorting: Arrays.sort(scores);
- Copying: int[] copy = Arrays.copyOf(scores, scores.length);
- Comparing: boolean isEqual = Arrays.equals(scores, copy);
- Filling: Arrays.fill(scores, 0); // Fill all elements with 0
(Note: Import java.util.Arrays for utility methods.)
10. Common Pitfalls
- Arrays are zero-indexed: array[0] is the first element.
- Fixed size: You cannot change the size of an array once its created.
- Use ArrayList if you need a resizable array.
What does .length do?
In Java, .length is used to get the number of elements in an array.
Java Arrays Reviewer
Example:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length); // Output: 5
Key Points:
- .length is a property (not a method) of arraysno parentheses are used.
- It returns the total number of elements the array can hold.
- Useful for loops, especially when you don't know the array size beforehand.
Important:
- For arrays: array.length
- For strings: string.length() this is a method, not a property.