Java Arrays and Lists

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.

Array Declaration

In Java, an array is declared using the following syntax:


dataType[] arrayName = new dataType[arraySize];

Array Example

Below is an example of how to declare and initialize an array in Java:


int[] numbers = {1, 2, 3, 4, 5};

ArrayList Declaration

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<>();

ArrayList Example

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);

Accessing Array Elements

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

Accessing ArrayList Elements

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