📝 Blog Post 1: Introduction to Arrays in Java

Introduction to Arrays in Java 🚀

Post 1 of the Cracking Java Arrays Series

If you're learning Java, you'll hear about arrays a lot. But what exactly is an array, and why should you care?

Let’s break it down with a simple explanation, beginner-friendly code, and real-world examples.


🔍 What is an Array?

In simple terms, an array is a container that holds a fixed number of elements of the same type.

Imagine a row of lockers. Each locker has a number (index), and each holds one item (value). That’s your array!


🎯 Why Use Arrays?

Let’s say you want to store marks of 5 students. Without arrays:

int mark1 = 80;
int mark2 = 85;
int mark3 = 90;
int mark4 = 70;
int mark5 = 95;

It works... but is repetitive and hard to manage.

With arrays:

int[] marks = {80, 85, 90, 70, 95};

Much cleaner! You can now access marks easily with:

System.out.println(marks[2]); // prints 90

⚠️ Array indexing in Java starts at 0.

🛠️ Declaring Arrays

There are two main ways:

✅ Method 1: Declare + Initialize

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

✅ Method 2: Declare first, then assign values

javaCopyEditint[] numbers = new int[5]; // Creates an array of size 5
numbers[0] = 10;
numbers[1] = 20;
// ... up to numbers[4]

🔗 Key Properties of Arrays

  • Fixed size (you can’t change the length after creation)

  • All elements must be of the same type

  • Length accessed via .length:

javaCopyEditSystem.out.println(numbers.length); // Output: 5

🚫 Common Mistake

javaCopyEditint[] a = new int[3];
a[3] = 10; // ❌ Error: ArrayIndexOutOfBoundsException

Arrays are zero-based, so valid indices are 0 to length - 1.


🔅 Mini Problem Statement: "Store and Print Student Marks"

Write a Java program that:

⛳ Creates an integer array to store the marks of 5 students

⛳ Initializes the array with sample marks

⛳ Prints the third student's mark

⛳ Prints the total number of students

⛳ Handles out-of-bounds access safely (demonstrates a common mistake).

public class StudentMarks {
    public static void main(String[] args) {
        // Declare and initialize an array
        int[] marks = {80, 85, 90, 70, 95};

        // Print the mark of the third student (index 2)
        System.out.println("Mark of 3rd student: " + marks[2]);

        // Print total number of students
        System.out.println("Total students: " + marks.length);

        // Common mistake demonstration
        try {
            System.out.println(marks[5]); // Invalid index
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Oops! You're trying to access an index out of range.");
        }
    }
}

☑️Output:

Mark of 3rd student: 90
Tota; students: 5
Oops! You're trying to access an index out of range.

1. Print an Array elements using for-each loop

  1. Create two arrays:

    • One for strings (names) containing names of people.

    • One for integers (numbers) containing numeric values.

  2. Use a for-each loop to iterate through each array:

    • Print each name from the names array.

    • Print each number from the numbers array.

  3. Output each element one by one using System.out.println() inside the loop.

This approach demonstrates how to declare arrays and traverse them using a for-each loop in Java.

public class Main{
  public static void main(String args[]){
    //String array
    String names[]={"Chaitanya", "Ajeet", "Rahul", "Hari"};

    //print array elements using for-each loop
    for(String str:names)
      System.out.println(str);

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

    //print array elements using for-each loop
    for(int num:numbers)
      System.out.println(num);
  }
}

☑️Output:

Chaitanya
Ajeet
Rahul
Hari
1
2
3
4
5

2. Find smallest number in an array

  1. Start by initializing an array with a set of integer values.

  2. Assume the first element of the array is the smallest and store it in a variable.

  3. Loop through the array from the beginning to the end.

  4. During each iteration, compare the current element with the stored smallest value.

  5. If a smaller value is found, update the stored value with this new one.

  6. After the loop completes, the stored value will be the smallest element in the array.

  7. Print the smallest value as the result.

public class Main {
  public static void main(String[] args) {

    //Initializing an int array
    int [] arr = new int [] {3, 8, 1, 12, 7, 99};
    //This element will store the smallest element of the array
    //Initializing with the first element of the array
    int smallestElement = arr[0];
    //Running the loop from first element till last element
    for (int i = 0; i < arr.length; i++) {
      //Compare each elements of array with smallestElement
      //If an element is smaller, store the element into smallestElement
      if(arr[i] < smallestElement)
        smallestElement = arr[i];
    }
    System.out.println("Smallest element of given array: " + smallestElement);
  }
}

☑️Output:

Smallest element of given array: 1

3. Find the largest element of an array

  1. Create a string array and initialize it with a few names.

  2. Create an integer array and initialize it with a set of numbers.

  3. Use a for-each loop to go through each element in the string array.

  4. For every element in the loop, print the current string.

  5. Repeat the same process for the integer array using a for-each loop.

  6. Print each number from the array one by one during the loop.

public class Main
{
    public static void main(String[] args) {

    //Initializing an int array
    int [] arr = new int [] {3, 8, 1, 12, 7, 99};
    //Initializing with the first element of the array
    int large = arr[0];
    //Running the loop from first element till last element
    for (int i = 0; i < arr.length; i++) {
      if(arr[i] >= large)
        large = arr[i];
    }
    System.out.println("Largest element of given array: " + large);


    }
}

☑️Output:

Largest element of given array: 99

✨ Quick Recap

Introduction to Arrays in Java covers the fundamentals of arrays, explaining them as containers for fixed-size, same-type elements. The article highlights the benefits of using arrays for efficient data management and demonstrates declaration, initialization, and access of array elements using Java code examples. It also addresses common mistakes, like ArrayIndexOutOfBoundsException, and includes practice problems such as finding the smallest and largest elements in an array. The content serves as the first part of the "Cracking Java Arrays" series, providing a foundation for understanding arrays and setting the stage for more advanced topics like one-dimensional arrays and array manipulation using loops.

Concepts CoveredDetails
What is an ArrayA container that stores elements of the same type in a fixed size structure
Why Arrays Are UsefulHelp manage collections of data more efficiently
Array Declaration & InitializationUsing both direct initialization and new keyword
Accessing ElementsUsing indices (starts from 0)
Array Length PropertyAccessed with .length
Common MistakesLike ArrayIndexOutOfBoundsException when accessing invalid indices

✅ Problems Practiced

  • Store and Print Student Marks - Hands-on array creation, indexing, and exception handling

  • Print Array Elements (for-each loop) - How to iterate over arrays using enhanced for-loops

  • Find the Smallest Element in an Array - Using a loop to track and compare elements

  • Find the Largest Element in an Array - Similar logic to smallest, but tracking the maximum


Try yourself:

HackerRank

🧭 What’s Next?

In the next blog post, we’ll dive deeper into:

One-Dimensional Arrays: Declaration, Initialization, and Access Patterns

We’ll also cover:

  • Using loops with arrays

  • User input and output

  • Real problems like reversing an array


💬 Have a question? Drop a comment.

🔁 Missed the series intro? Click here to go back.


📌 This blog is part of the “Cracking Java Arrays” series. Follow to stay updated on upcoming posts!

0
Subscribe to my newsletter

Read articles from Gnaneshwari Gunasekaran directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gnaneshwari Gunasekaran
Gnaneshwari Gunasekaran

Hi, I’m Gnaneshwari — a passionate Full-Stack Developer with hands-on experience in building robust web applications using Angular 13+ and Java Spring Boot. My journey began with a strong academic foundation (CGPA: 8.99) and quickly evolved into real-world experience, where I contributed to a large-scale Warehouse Management System (WMS) project. During my internship and full-time experience, I took ownership of key modules including ASN workflows, Sales Order Management, and Inventory Operations, seamlessly connecting frontend interfaces with backend logic. I’ve worked across multiple layers of enterprise applications—designing APIs, implementing entity relationships, and crafting responsive UIs using Angular Material and SCSS. I enjoy building scalable and user-friendly solutions, and I’m constantly exploring new tools and practices to sharpen my skills. Whether it's optimizing API interactions, enhancing user experiences, or debugging complex issues, I take pride in delivering clean, maintainable code. 🔍 Currently Exploring: CometChat, Real-time Communication, GraphQL, and Building Chat Applications 🚀 Looking for: Full-time roles, freelance projects, or collaborations where I can grow and make an impact.