In today's lesson, we'll explore arrays in Java, a versatile and fundamental data structure. An array is a collection of elements of the same data type, stored in a contiguous memory location. Once created, the size of an array is fixed, and elements can be accessed via their index.
The beauty of arrays lies in their ability to efficiently store and access large amounts of data by index. By the end of this lesson, you'll be able to create, manipulate, and understand the unique applications of arrays in Java.
Arrays are a core part of Java programming, allowing you to define collections of elements of the same type. There are two primary ways to create arrays in Java: using array literals and using constructors with the new
keyword.
-
Array Literals: An array can be declared and initialized with specific values directly using an array literal. This involves enclosing the elements within curly braces
{}
. -
Using Constructors: Arrays can also be created using the
new
keyword, followed by the type and square brackets[]
. This approach specifies the array's type and initializes it with values or specifies the size of the array.
Here's an example illustrating array creation using both methods:
Java1class ArrayExample { 2 public String[][] createArrays() { 3 String[] arrayLiteral = {"apple", "banana", "cherry"}; // Using array literals 4 String[] fromConstructor = new String[] {"apple", "banana", "cherry"}; // Using constructor 5 return new String[][] {arrayLiteral, fromConstructor}; 6 } 7} 8 9public class Solution { 10 public static void main(String[] args) { 11 ArrayExample arrayExample = new ArrayExample(); 12 String[][] arrays = arrayExample.createArrays(); 13 System.out.println(String.join(", ", arrays[0])); // Output: apple, banana, cherry 14 System.out.println(String.join(", ", arrays[1])); // Output: apple, banana, cherry 15 } 16}
This example demonstrates how to create arrays using both the array literal method and the constructor method, providing the same resulting arrays in both cases.
An array in Java is an ordered collection of elements that are of the same type, including numbers, strings, objects, and even other arrays.
Consider this Java array declaration as an example:
Java1class ArrayExample { 2 public Object[] createMixedArray() { 3 return new Object[] {"apple", 42, true, new String("banana"), new int[] {1, 2, 3}}; 4 } 5} 6 7public class Solution { 8 public static void main(String[] args) { 9 ArrayExample arrayExample = new ArrayExample(); 10 Object[] mixedArray = arrayExample.createMixedArray(); 11 for (Object element : mixedArray) { 12 System.out.println(element); 13 } 14 // Output: 15 // apple 16 // 42 17 // true 18 // banana 19 // [I@7b23ec81 (array memory reference) 20 } 21}
Just like strings, array elements are accessible via indexes. Indexes in Java arrays are zero-based. For example, the first element has an index of 0.
The length
property of an array returns the number of elements present in the array and can be used to easily determine its size or iterate over the array.
Consider the following example that depicts inspecting and modifying arrays, as well as demonstrating the length
property:
Java1import java.util.Arrays; 2 3class ArrayExample { 4 public void inspectArray() { 5 String[] myArray = {"apple", "banana", "cherry", "durian", "elderberry"}; 6 System.out.println(myArray[1]); // Output: banana 7 System.out.println(myArray[myArray.length - 1]); // Output: elderberry 8 9 String[] slice = Arrays.copyOfRange(myArray, 2, 4); 10 System.out.println(String.join(", ", slice)); // Output: cherry, durian 11 12 String[] newArray = {myArray[1], myArray[2], "dragonfruit"}; 13 System.out.println(String.join(", ", newArray)); // Output: banana, cherry, dragonfruit 14 } 15} 16 17public class Solution { 18 public static void main(String[] args) { 19 ArrayExample arrayExample = new ArrayExample(); 20 arrayExample.inspectArray(); 21 } 22}
Java arrays allow a range of operations. Using the Java Collections framework and streams, you can perform various operations on arrays succinctly. Here are a few examples:
Java1import java.util.Arrays; 2import java.util.stream.Stream; 3 4class ArrayExample { 5 public void arrayOperations() { 6 String[] array1 = {"apple", "banana"}; 7 String[] array2 = {"cherry", "durian"}; 8 9 String[] array3 = Stream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray(String[]::new); 10 System.out.println(String.join(", ", array3)); // Output: apple, banana, cherry, durian 11 12 String[] array4 = Stream.concat(Stream.concat(Arrays.stream(array1), Arrays.stream(array1)), Arrays.stream(array1)).toArray(String[]::new); 13 System.out.println(String.join(", ", array4)); // Output: apple, banana, apple, banana, apple, banana 14 15 System.out.println(Arrays.asList(array1).contains("apple")); // Output: true 16 17 String[] mappedArray = Arrays.stream(array1).map(fruit -> fruit + " pie").toArray(String[]::new); 18 System.out.println(String.join(", ", mappedArray)); // Output: apple pie, banana pie 19 } 20} 21 22public class Solution { 23 public static void main(String[] args) { 24 ArrayExample arrayExample = new ArrayExample(); 25 arrayExample.arrayOperations(); 26 } 27}
An array can contain another array, resulting in a nested array structure. Each element within a nested array structure is itself a reference to another array. In a nested array, you can access elements by chaining indices. The first index accesses an element within the top-level array, and the subsequent index(es) access elements within the sub-array. When accessing an inner array, you need to cast it to (Object[])
to avoid type mismatches, as Java stores arrays as references within the parent array. Here's an example of creating and accessing a nested array:
Java1class ArrayExample { 2 public Object[] createNestedArray() { 3 return new Object[] {"apple", new Object[] {"banana", "cherry"}}; 4 } 5} 6 7public class Solution { 8 public static void main(String[] args) { 9 ArrayExample arrayExample = new ArrayExample(); 10 Object[] nestedArray = arrayExample.createNestedArray(); 11 System.out.println(nestedArray[0]); // Output: apple 12 13 Object[] subArray = (Object[]) nestedArray[1]; 14 System.out.println(subArray[0]); // Output: banana 15 System.out.println(subArray[1]); // Output: cherry 16 } 17}
You can create complex nested arrays where each element can be an object containing arrays. Consider the following example with car manufacturers and their models:
Java1class Car { 2 private String name; 3 private String[] models; 4 5 public Car(String name, String[] models) { 6 this.name = name; 7 this.models = models; 8 } 9 10 public String getName() { 11 return name; 12 } 13 14 public String[] getModels() { 15 return models; 16 } 17} 18 19class ArrayExample { 20 public Car[] createNestedObjectArray() { 21 return new Car[] { 22 new Car("Ford", new String[] {"Fiesta", "Focus", "Mustang"}), 23 new Car("BMW", new String[] {"320", "X3", "X5"}), 24 new Car("Fiat", new String[] {"500", "Panda"}) 25 }; 26 } 27} 28 29public class Solution { 30 public static void main(String[] args) { 31 ArrayExample arrayExample = new ArrayExample(); 32 Car[] cars = arrayExample.createNestedObjectArray(); 33 for (Car car : cars) { 34 System.out.println(car.getName() + ": " + String.join(", ", car.getModels())); 35 } 36 37 // Access elements in the nested object array 38 System.out.println(String.join(", ", cars[0].getModels())); // Output: Fiesta, Focus, Mustang 39 System.out.println(cars[1].getName()); // Output: BMW 40 System.out.println(cars[2].getModels()[1]); // Output: Panda 41 } 42}
This demonstrates how nested arrays can be used in complex structures, making it easier to organize and access data.
Great work! In this lesson, you've learned what arrays are and how to create, inspect, and operate on them in Java. You've also learned some advanced concepts like nested arrays and how to use streams for array operations.
Moving forward, we encourage you to practice creating and manipulating arrays in different contexts. Experiment with these examples by tweaking and testing them. Continuous practice is key to mastering programming in Java. Let's continue to explore more advanced topics!