Java Arrays
Arrays in Java are objects that store multiple values of the same type. An array can be declared by specifying the data type of the elements it will store and the number of elements in square brackets following the array name.
Here is an example of declaring and initializing an array of integers in Java:
int[] numbers = {1, 2, 3, 4, 5};
int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = i + 1; }
System.out.println("The first element is: " + numbers[0]);
for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + " is: " + numbers[i]); }
for (int number : numbers) { System.out.println("Element is: " + number); }
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("The element at position (1, 2) is: " + matrix[1][2]);
for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.println("Element at position (" + i + ", " + j + ") is: " + matrix[i][j]); } }
However, there are utility classes such as ArrayList in the java.util package that provide dynamic arrays, which can grow or shrink as needed. ArrayList provides methods such as add and remove to add and remove elements, and it automatically resizes itself as needed.
Here is an example of using an ArrayList to store integers:
List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("The size of the list is: " + numbers.size()); System.out.println("The first element is: " + numbers.get(0)); numbers.remove(1); System.out.println("The size of the list after removing an element is: " + numbers.size());
You can also use a foreach loop to loop over the elements in an ArrayList:
for (int number : numbers) { System.out.println("Element is: " + number); }
Additionally, arrays can only store elements of a single type, whereas ArrayList can store elements of any type using generics. For example, you can create an ArrayList of strings, an ArrayList of integers, or an ArrayList of any other type.
List<String> names = new ArrayList<>(); names.add("John"); names.add("Jane"); names.add("Jim"); for (String name : names) { System.out.println("Name is: " + name); }