DEV Community

SIVAGANESH L
SIVAGANESH L

Posted on

Understanding Java Arrays: A Beginner's Perspective

What is an Array in Java?
In simple terms, an array is like a row of containers that can store multiple values of the same type.

Why Do We Use Arrays in Java?
Imagine you want to store the marks of 3 students. You might do this:

int mark1 = 10;
int mark2 = 20;
int mark3 = 30;
Enter fullscreen mode Exit fullscreen mode

But what if there are 100 students?

Using so many separate variables becomes difficult to write, read, and manage. That’s why we use arrays.

When we Should Use an Array?

You know how many values you need to store.

All values are of the same type (e.g. all integers, all strings).

You want to loop through the data easily.

You need fast access to elements using index numbers.

Array example:

int[] numbers = {1, 2, 3, 4, 5}; //Here, numbers is an array that holds 5 integers.
String[] fruits = {"Apple", "Banana", "Mango"};
boolean[] flags = {true, false, true};
Enter fullscreen mode Exit fullscreen mode

How to Declare an Array
There are two main steps:

Declare the array:

int[] myArray;            // Declaration
Enter fullscreen mode Exit fullscreen mode

Initialize it with values or size:

myArray = new int[3];     // Initialization with size
Enter fullscreen mode Exit fullscreen mode

You can also do both in one line:

int[] myArray = new int[3];
Enter fullscreen mode Exit fullscreen mode

Storing Values in an Array:
Array uses indexes to store values and index starts from 0.

myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
Enter fullscreen mode Exit fullscreen mode

Array looks like [10,20,30]

Accessing Array Elements

System.out.println(myArray[1]); //Output: 20
Enter fullscreen mode Exit fullscreen mode

Looping Through Arrays

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}
Enter fullscreen mode Exit fullscreen mode

When Not to Use Arrays?

You don’t know the size of elements in advance.

You need to frequently add or remove elements.

Top comments (0)