🧰 Java Basics to Intermediate
Estimated reading: 3 minutes 275 views

Java Arrays – Complete Guide with Syntax, Examples & Best Practices


Introduction – Why Arrays Matter in Java

Imagine needing to store the marks of 100 students. Creating 100 separate variables would be chaotic.
That’s where arrays come in β€” allowing you to store multiple values of the same type in a single variable.

By the end of this article, you’ll learn:

  • What arrays are and how they work in Java
  • Syntax for declaring, initializing, and accessing arrays
  • How to loop through arrays using for and for-each
  • Real-world examples, best practices, and common pitfalls

What is an Array in Java?

An array is a container object that holds a fixed number of elements of the same type, accessible using an index.

Important Note: Java arrays have zero-based indexing.


Declaring and Initializing Arrays

1. Declaration Only

int[] numbers;

2. Declaration + Memory Allocation

int[] numbers = new int[5];  // holds 5 integers (default 0)

3. Declaration + Initialization with Values

int[] numbers = {10, 20, 30, 40, 50};

Explanation:

  • int[] β†’ declares an integer array
  • {} β†’ initializes it with values
  • new int[5] β†’ allocates space for 5 elements with default values

Accessing Elements in Arrays

int[] scores = {90, 85, 70};
System.out.println(scores[1]);  // 85

Explanation:

  • Index 0 = first element
  • Index 1 = second element
  • Accessed using array[index]

Accessing an index outside bounds throws ArrayIndexOutOfBoundsException.


Looping Through Arrays

1. Standard for Loop

for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

2. Enhanced for Loop (for-each)

for (int score : scores) {
    System.out.println(score);
}

Explanation:

  • scores.length gives array size
  • Enhanced loop simplifies read-only traversal

Modify Array Elements

int[] numbers = {1, 2, 3};
numbers[0] = 10;
System.out.println(numbers[0]);  // 10

Arrays are mutable: you can update any index with a new value.


Real-World Example: Finding Maximum in Array

int[] data = {12, 45, 22, 89, 5};
int max = data[0];

for (int i = 1; i < data.length; i++) {
    if (data[i] > max) {
        max = data[i];
    }
}

System.out.println("Max: " + max);

Explanation:

  • Compares each value with max
  • Updates max if a larger value is found

Multi-Dimensional Arrays

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

System.out.println(matrix[1][2]);  // 6

Explanation:

  • 2D array = array of arrays
  • Accessed using array[row][column]

Commonly used in grid-based apps, games, and mathematical computations.


Best Practices for Java Arrays

Tips:

  • Always check .length before accessing indices
  • Prefer ArrayList for dynamic resizing needs
  • Use enhanced for loop when not modifying values

Pitfalls:

  • Arrays have fixed size β€” cannot grow after creation
  • Be careful with off-by-one errors (i <= array.length )

Java Arrays vs ArrayList

FeatureArrayArrayList
SizeFixedDynamic
TypePrimitive & ObjectObjects only (generic)
SyntaxSimplerMore flexible
PerformanceFasterSlightly slower

Summary

Java arrays are essential for storing fixed-size groups of related values. Mastering them lets you write efficient, clean, and logical Java code.

Key Takeaways:

  • Arrays store multiple values of the same type
  • Indexing starts at 0
  • Use loops to access or modify data
  • For dynamic storage, consider using collections like ArrayList

FAQs – Java Arrays

Can Java arrays hold different data types?

No. Arrays in Java can only hold elements of the same type.

What is the default value of an array element?

  • int, long, byte, short β†’ 0
  • float, double β†’ 0.0
  • boolean β†’ false
  • char β†’ '\u0000' (null character)
  • Object types β†’ null

Can I change the size of an array?

No. Once created, the size of an array is fixed. Use ArrayList for resizable collections.

How to get the length of an array?

Use array.length (no parentheses β€” it’s a property, not a method).

How to copy one array into another?

Use System.arraycopy() or Arrays.copyOf() for efficient copying.


Share Now :
Share

Java Arrays

Or Copy Link

CONTENTS
Scroll to Top