Arrays
Quick Reference
Array Declaration and Initialization
When to Use Arrays
- Use arrays when you need a fixed-size collection of elements of the same type.
- Ideal for scenarios where you need fast access to elements using an index.
- Arrays are memory-efficient and provide better performance for fixed-size data.
Drawbacks of Arrays
- Fixed Size: Size cannot be changed after declaration.
- Homogeneous Data: Only stores elements of the same type.
- Limited Methods: No built-in methods for resizing, searching, or sorting.
Jagged Arrays
What are Jagged Arrays?
Arrays of arrays where sub-arrays can have different sizes, useful for non-rectangular data like triangles or sparse matrices.
Arrays of Objects
Arrays of Objects
- Arrays of objects store references to the objects, not the objects themselves.
- Each object in the array must be manually created and initialized.
- If an object is not initialized, its reference will be
null. In this case, trying to access its properties or methods will result in aNullPointerException.
class Person {
String name;
Person(String name) {
this.name = name;
}
}
Person[] people = new Person[3];
people[0] = new Person("Alice");
people[1] = new Person("Bob");
people[2] = new Person("Charlie");
for (Person person : people) {
System.out.println(person.name);
}
// Output:
// Alice
// Bob
// Charlie