Arrays are a fundamental data structure in many programming languages. They are used to store and manage collections of data. In this tutorial, we will cover the basics of arrays and their usage in programming.

What is an Array?

An array is a collection of elements of the same type. Each element in the array is called an "array element" and is accessed by its index. The index is a unique identifier for each element in the array.

Types of Arrays

  • Primitive Arrays: These arrays contain elements of primitive data types, such as integers, floating-point numbers, and characters.
  • Reference Arrays: These arrays contain references to objects, such as objects of a class or instances of a class.

How to Declare an Array

To declare an array, you use square brackets [] after the data type. Here is an example:

int[] numbers = new int[5];

This declares an array named numbers that can hold 5 integers.

Accessing Elements in an Array

Elements in an array are accessed using their index. The index starts from 0 for the first element. Here's how you can access the first element:

int firstNumber = numbers[0];

Modifying Elements in an Array

You can modify elements in an array by assigning a new value to an element using its index:

numbers[0] = 10;

Arrays in Action

Here is an example of using arrays to store a list of numbers and performing operations on them:

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

// Adding a new element to the array
int[] newNumbers = new int[numbers.length + 1];
System.arraycopy(numbers, 0, newNumbers, 0, numbers.length);
newNumbers[newNumbers.length - 1] = 6;

// Finding the sum of the elements in the array
int sum = 0;
for (int i = 0; i < newNumbers.length; i++) {
    sum += newNumbers[i];
}

// Output the sum
System.out.println("The sum is: " + sum);

For more information on arrays and their advanced usage, check out our Advanced Arrays Tutorial.

Conclusion

Arrays are a powerful tool for managing collections of data in programming. Understanding how to declare, access, and modify arrays is essential for any programmer.

Arrays in Programming