JAVA ARRAYS

Prosper
2 min readAug 6, 2021

Java array is an object which contains elements of a similar data type. In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the serializable as well as cloneable interfaces. We can store primitive values or objects in an array in Java.

Following are some important points about Java arrays.

  • In Java all arrays are dynamically allocated.(discussed below)
  • Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++ where we find length using sizeof.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each have an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an integer or short value and not long.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.

Array can contain primitives (String, char, etc.) as well as object (or non-primitive) references of a class depending on the definition of the array. In case of primitive data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in heap segment.

Creating, Initializing, and Accessing an Array

import java.util.ArrayList;
import java.util.Collections;
public class FirstPart {public static void main(String[] args) {
ArrayList<String> games = new ArrayList<String>();
games.add("Minecraft");
games.add("Call Of Duty");
games.add("FIFA");
games.add("Far Cry");
games.add("Free Fire");
games.add("GTA");
games.set(2, "tako");

The following is an example of an Array list with games in it.

Access an Item

To access an element in the ArrayList, use the get() method and refer to the index number.

Example:

games.get(0);

Note: Array indexes start with 0 (0 is the first element. 1 is the second element, etc.)

Change an Item

To modify an element, use the set() method and refer to the index number.

Example:

games.set(0, "Assassin's Creed");

Remove an Item

To remove an element, use the remove() method and refer to the index number.

Example:

games.remove(0);

Note: To remove all the elements in the ArrayList, use the clear() method:

Example:

games.clear();

ArrayList Size

To find out how many elements an ArrayList have, use the size method.

Example:

cars.size();

Loop Through an ArrayList

--

--