Arrays and lists are fundamental data structures in Java used to store collections of elements. They provide a way to organize and manipulate data efficiently.
In Java, an array is declared using the following syntax:
dataType[] arrayName = new dataType[arraySize];
Below is an example of how to declare and initialize an array in Java:
int[] numbers = {1, 2, 3, 4, 5};
ArrayList is a part of the Java Collections Framework and provides dynamic array-like functionality. It is declared and initialized as follows:
import java.util.ArrayList;
ArrayList<dataType> listName = new ArrayList<>();
Below is an example of how to declare and initialize an ArrayList in Java:
import java.util.ArrayList;
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
Array elements can be accessed using their index. Indexing starts at 0.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Output: 1
ArrayList elements can be accessed using the get() method, specifying the index of the element.
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println(numbers.get(0)); // Output: 1