Arrays in Java : The Complete Beginner-Friendly Guide

Arrays in Java : The Complete Beginner-Friendly Guide

Java Arrays Tutorial for Beginners: In this guide, you will learn array declaration, array creation, array initialization, multidimensional and jagged arrays, anonymous arrays, array element assignments, and array variable assignments with easy Java examples.

🤔 What is an Array in Java?

If you want to store a single value, you can use a single variable.

int x = 10;

For 10 values, you may think of creating 10 variables. But what about 100 or 1000 values? Will you declare 1000 variables? 😵

Of course not! It is not a good programming practice. To solve this problem, we use Arrays.

  • Arrays are used to store a large number of values.
  • We can access array elements using an index.
  • Arrays are fixed in size.
  • Arrays hold homogeneous data values.
📌 Definition:
An array is an indexed collection of a fixed number of homogeneous elements.

1️⃣ Array Declaration in Java

One-Dimensional Array (1D)

int[] x;   // Valid ✅ Recommended
int []x;   // Valid ✅
int x[];   // Valid ✅

int[6] x;  // Invalid ❌
💡 At the time of array declaration, we cannot specify the size of the array.

Two-Dimensional Array (2D)

int[][] x;   // Valid ✅
int [][]x;   // Valid ✅
int x[][];   // Valid ✅
int[] []x;   // Valid ✅
int[] x[];   // Valid ✅

Interesting Declaration Examples 🧠

int[] a, b;        // a → 1D, b → 1D

int[] a[], b;      // a → 2D, b → 1D

int[] a[], b[];    // a → 2D, b → 2D

int[][] a, b;      // a → 2D, b → 2D

int[][] a, b[];    // a → 2D, b → 3D

int[][] a, []b;    // Compile-Time Error ❌
⚠️ The []b facility is available only for the first variable in a declaration.

Three-Dimensional Array (3D)

int[][][] a;   // Valid ✅
int [][][]a;   // Valid ✅
int a[][][];   // Valid ✅
int[] [][]a;   // Valid ✅
int[] a[][];   // Valid ✅
int[][] []a;   // Valid ✅

2️⃣ Array Creation in Java

int[] a = new int[3];

System.out.println(a.getClass().getName());

// Output:
[I

Every array in Java is an object. Hence, we can create arrays using the new operator.

For every array type, a corresponding class exists internally. These class names are available at the JVM level and are not normally used directly by programmers.

Array TypeInternal Class Name
int[][I
int[][][[I
double[][][[D
short[][S
byte[][B
boolean[][Z

Array Size is Mandatory

At the time of array creation, we must specify the size.

int[] a = new int[];    // Compile-Time Error ❌

int[] a = new int[0];   // Valid ✅
int[] a = new int[3];   // Valid ✅

int[] a = new int[-3];  // Compiles ✅
// Runtime Exception: NegativeArraySizeException ❌

What Types Can Be Used as Array Size?

We can use values that are implicitly converted to int, such as byte, short, and char.

int[] x = new int[10];     // Valid ✅
int[] x = new int['a'];    // Valid ✅ ('a' = 97)

byte b = 20;
int[] x1 = new int[b];     // Valid ✅

short s = 40;
int[] x2 = new int[s];     // Valid ✅

int[] x3 = new int[10L];   // Compile-Time Error ❌
// possible lossy conversion from long to int

Jagged Arrays — Array of Arrays

In Java, a multidimensional array is actually an array of arrays. This allows different rows to have different sizes.

int[][] x = new int[2][];

x[0] = new int[3];
x[1] = new int[5];

Here, the 2D array contains two 1D arrays: one of size 3 and another of size 5.

✅ Main advantage: memory can be used more efficiently when rows need different sizes.

🧠 Quiz: Which Array Creations Are Valid?

1.  int[] a = new int[];
2.  int[] a = new int[3];
3.  int[][] a = new int[][];
4.  int[][] a = new int[3][];
5.  int[][] a = new int[][4];
6.  int[][] a = new int[3][4];
7.  int[][][] a = new int[3][4][5];
8.  int[][][] a = new int[3][4][];
9.  int[][][] a = new int[3][][5];
10. int[][][] a = new int[][4][5];
👀 Click to See Answer

Valid: 2, 4, 6, 7, 8

Invalid: 1, 3, 5, 9, 10

Once a dimension is left empty, the dimensions after it cannot have sizes during the same array creation.

3️⃣ Array Initialization in Java

int[] a = new int[3];

System.out.println(a);
// Example output: [I@659e0bfd

System.out.println(a[0]);
// Output: 0

When we print a reference variable, Java uses its string representation. The default Object.toString() format looks like:

className@hexadecimalHashCode
📌 The exact hash-code part may be different every time you run the program.

Example 1: Complete 2D Array

int[][] a = new int[2][3];

System.out.println(a);        // Example: [[I@659e0bfd
System.out.println(a[0]);     // Example: [I@68ee0bfd
System.out.println(a[0][0]);  // 0

Example 2: Incomplete 2D Array

int[][] a = new int[2][];

System.out.println(a);        // Example: [[I@659e0bfd
System.out.println(a[0]);     // null
System.out.println(a[0][0]);  // Runtime Exception ❌
// NullPointerException

a[0] is still null. So trying to access a[0][0] causes a NullPointerException.

Example 3: Accessing Array Elements

int[] x = new int[6];

x[0] = 10;
x[1] = 20;
x[2] = 30;
x[3] = 40;
x[4] = 50;
x[5] = 60;

x[6] = 70;   // Runtime Exception ❌
x[-6] = 70;  // Runtime Exception ❌
// ArrayIndexOutOfBoundsException

x[2.5] = 9;  // Compile-Time Error ❌
// possible lossy conversion from double to int

Declaration, Creation & Initialization

int[] x;          // Declaration
x = new int[2];   // Creation
x[0] = 10;        // Initialization
x[1] = 20;        // Initialization

We can do everything in a single line:

int[] x = {10, 20, 30};

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

4️⃣ length vs length() in Java

length — For Arrays

length is a final variable used to find the size of an array.

int[] a = new int[2];

System.out.println(a.length);    // 2

System.out.println(a.length());  // Compile-Time Error ❌
// cannot find symbol: method length()

length() — For Strings

length() is a method used to find the number of characters in a String.

String s = "java";

System.out.println(s.length());  // 4

System.out.println(s.length);    // Compile-Time Error ❌
// cannot find symbol: variable length
Used WithUse
Arrayarray.length
Stringstring.length()

5️⃣ Anonymous Arrays in Java

An anonymous array is an array without a name. It is useful when we need an array only once.

class Main {
    public static void main(String[] args) {
        System.out.println(sum(new int[]{10, 20, 30}));
    }

    public static int sum(int[] a) {
        int total = 0;

        for (int x : a)
            total += x;

        return total;
    }
}

Important Points

new int[]{10, 20, 30};             // Valid ✅

new int[3]{10, 20, 30};            // Invalid ❌

new int[][]{{10}, {20, 30}};       // Valid ✅
💡 If we give a name to an anonymous array, it is no longer anonymous.
int[] x = new int[]{10, 20, 30};

6️⃣ Array Element Assignments in Java

Case 1: Primitive Type Arrays

int[] x = new int[6];

x[0] = 10;     // Valid ✅
x[1] = 'a';    // Valid ✅

byte b = 20;
x[2] = b;      // Valid ✅

short s = 30;
x[3] = s;      // Valid ✅

x[4] = 10L;    // Invalid ❌
// long cannot be assigned to int without explicit casting

Case 2: Object Type Arrays

Object[] a = new Object[10];

a[0] = new Object();       // Valid ✅
a[1] = new String("java"); // Valid ✅
a[2] = new int[10];        // Valid ✅

Why is int[] allowed in an Object[]? Because every array in Java is an object.

Number[] n = new Number[4];

n[0] = Integer.valueOf(10); // Valid ✅
n[1] = Double.valueOf(10.5);// Valid ✅
n[2] = new String("java");  // Invalid ❌
✅ For a class-type array, elements can be objects of the declared class or its child classes.

Case 3: Interface Type Arrays

Runnable[] r = new Runnable[3];

r[0] = new Thread();       // Valid ✅
r[1] = new String("ram");  // Invalid ❌

Thread implements the Runnable interface, but String does not.

✅ For an interface-type array, objects of its implementation classes are allowed.

7️⃣ Array Variable Assignments in Java

int[] x = {10, 20, 30};
char[] ch = {'a', 'b', 'c'};

int[] b = x;   // Valid ✅

int[] c = ch;  // Invalid ❌
// char[] cannot be converted to int[]

Primitive widening may happen for individual values, but Java does not automatically convert one primitive array type into another primitive array type.

AssignmentResult
char → intValid ✅
char[] → int[]Invalid ❌
int → doubleValid ✅
int[] → double[]Invalid ❌
float → intInvalid ❌
float[] → int[]Invalid ❌
String → ObjectValid ✅
String[] → Object[]Valid ✅
📌 Remember: String[] → Object[] is valid because arrays of reference types support assignment based on the parent-child relationship.

❓ Frequently Asked Questions About Java Arrays

Are arrays objects in Java?

Yes. Every array in Java is an object and is created using the new operator when explicit array creation is used.

Can we change the size of an array in Java?

No. Arrays are fixed in size. Once an array is created, its length cannot be changed.

Can a Java array store different data types?

A primitive array stores values of its declared primitive type or compatible values. Reference-type arrays can store compatible objects based on inheritance or interface relationships.

What is the difference between length and length() in Java?

Use length for arrays and length() for String objects.

What is a jagged array in Java?

A jagged array is a multidimensional array whose rows can have different lengths. Java supports this through its array-of-arrays approach.

📝 Quick Summary

  • An array stores a fixed number of homogeneous elements.
  • Array elements are accessed using an index starting from 0.
  • Every array in Java is an object.
  • Array size must be specified during creation.
  • Java supports jagged arrays using the array-of-arrays approach.
  • Use length for arrays and length() for Strings.
  • Anonymous arrays are useful when an array is required only once.
  • Primitive array types are not automatically converted into other primitive array types.
  • Reference-type arrays support compatible parent-child assignments.

🎯 One Last Question!

What happens when we execute the following code?

int[][] a = new int[2][];

System.out.println(a[0]);
System.out.println(a[0][0]);

A) Prints 0 and 0

B) Prints null and then throws NullPointerException

C) Compile-Time Error

D) ArrayIndexOutOfBoundsException

🔍 Check Answer

Answer: B ✅

a[0] is null. Accessing a[0][0] therefore causes a NullPointerException.

☕ Want to Learn More About Java? Explore simple and beginner-friendly Java tutorials and continue your Java learning journey step by step 🚀 Continue Your Java Journey →

Comments

Popular posts from this blog

Java Roadmap

Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-2)

Identifiers