CodeToConcept
About

java

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

JavaHTMLCSS

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Single Dimensional Array in Java

Run each complete program separately. Its required helper classes and imports are included in the same code block. Short syntax fragments explain individual operations.

Introduction

A one-dimensional array gives each element a numbered position. For example, we can keep a week's reading times in one int array and use an index to choose a day. The array keeps its length after creation; changing an element does not change that length.

Suppose we want to store the marks of five students.

Without an array, we might write:

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

This approach becomes difficult to manage when the number of values increases.

Using an array, we can store all the values using a single variable:

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

Now the values are stored inside the marks array.

Index:     0    1    2    3    4
           ↓    ↓    ↓    ↓    ↓
         +----+----+----+----+----+
marks →  | 80 | 75 | 90 | 85 | 70 |
         +----+----+----+----+----+

Java arrays use zero-based indexing, which means the first element is stored at index 0.

What is a Single Dimensional Array?

A Single Dimensional Array is an array where elements are arranged in a single sequence.

For example:

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

The array can be represented as:

Index:      0     1     2     3     4
Value:     10    20    30    40    50

To access an element, use:

arrayName[index]

For example:

numbers[0]

returns:

10

and:

numbers[3]

returns:

40

Why Do We Need Arrays?

Arrays are useful when we need to store multiple values of the same type.

For example, suppose we need to store the temperatures of seven days.

Without an array:

double day1 = 32.5;
double day2 = 31.8;
double day3 = 33.1;
double day4 = 34.0;
double day5 = 32.9;
double day6 = 31.5;
double day7 = 30.8;

Using an array:

double[] temperatures = {
    32.5, 31.8, 33.1, 34.0, 32.9, 31.5, 30.8
};

Now all seven values are represented by:

temperatures

This makes the program easier to manage and process.

Declaring a Single Dimensional Array

There are two valid ways to declare an array.

Syntax 1

dataType[] arrayName;

Example

int[] numbers;

Syntax 2

dataType arrayName[];

Example

int numbers[];

Both are valid, but the first form is generally preferred:

int[] numbers;

because it clearly indicates that numbers is an array of int.

Creating an Array

After declaring an array, we can create it using the new keyword.

int[] numbers = new int[5];

Here:

int       → element data type
[]        → indicates an array
numbers   → array variable
new       → creates an array object
int[5]    → creates space for 5 integers

The array contains five positions:

Index:    0    1    2    3    4
Value:    0    0    0    0    0

The values are 0 because int array elements receive their default value when the array is created.

Program 1: Creating an Array

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = new int[5];
 
        System.out.println(numbers.length);
    }
}

Output

5

The length property tells us how many elements the array can contain.

Initializing an Array

We can assign values to an array using indexes.

int[] numbers = new int[5];
 
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

The array becomes:

Index:    0    1    2    3    4
Value:   10   20   30   40   50

Program 2: Initializing an Array Using Index

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = new int[5];
 
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;
 
        System.out.println(numbers[0]);
        System.out.println(numbers[1]);
        System.out.println(numbers[2]);
        System.out.println(numbers[3]);
        System.out.println(numbers[4]);
    }
}

Output

10
20
30
40
50

Initializing an Array Using Array Literal

If the values are already known, we can initialize the array directly.

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

Java automatically determines the array size from the number of elements.

The above statement creates an array of length 5.

Program 3: Array Initialization Using Array Literal

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        System.out.println(numbers[0]);
        System.out.println(numbers[2]);
        System.out.println(numbers[4]);
    }
}

Output

10
30
50

Accessing Array Elements

An array element can be accessed using its index.

arrayName[index]

For example:

int[] numbers = {10, 20, 30, 40, 50};
 
System.out.println(numbers[0]);

Output:

10

The first element is always at index 0.

Program 4: Accessing an Array Element

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] marks = {80, 75, 90, 85, 70};
 
        System.out.println("First Mark: " + marks[0]);
        System.out.println("Third Mark: " + marks[2]);
        System.out.println("Last Mark: " + marks[4]);
    }
}

Output

First Mark: 80
Third Mark: 90
Last Mark: 70

Modifying an Array Element

Array elements can be changed after the array has been created.

For example:

int[] numbers = {10, 20, 30};
 
numbers[1] = 100;

The array changes from:

10  20  30

to:

10  100  30

Program 5: Modifying an Array Element

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30};
 
        System.out.println("Before: " + numbers[1]);
 
        numbers[1] = 100;
 
        System.out.println("After: " + numbers[1]);
    }
}

Output

Before: 20
After: 100

Array Index

Array indexing starts from 0.

For:

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

the indexes are:

Index:    0    1    2    3
Value:   10   20   30   40

Therefore:

numbers[0] → 10
numbers[1] → 20
numbers[2] → 30
numbers[3] → 40

The last valid index is:

array.length - 1

For an array of length 4:

Last index = 4 - 1 = 3

Program 6: Accessing the Last Element

Instead of directly writing the last index, we can use:

numbers[numbers.length - 1]

Example

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        int lastElement = numbers[numbers.length - 1];
 
        System.out.println("Last Element: " + lastElement);
    }
}

Output

Last Element: 50

Array Length

Every Java array has a length property.

Example

int[] numbers = {10, 20, 30, 40};
 
System.out.println(numbers.length);

Output:

4

Remember:

numbers.length

is correct.

Do not write:

numbers.length()

For arrays, length is a property.

Program 7: Using Array Length

public class HelloWorld {
 
    public static void main(String[] args) {
 
        String[] languages = {
            "Java",
            "Python",
            "C++",
            "JavaScript"
        };
 
        System.out.println("Number of Languages: " + languages.length);
    }
}

Output

Number of Languages: 4

Traversing an Array Using for Loop

Traversing an array means accessing each element one by one.

A for loop is commonly used for this purpose.

int[] numbers = {10, 20, 30, 40, 50};
 
for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

Here:

i

represents the current index.

Program 8: Traversing an Array

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        for (int i = 0; i < numbers.length; i++) {
 
            System.out.println(numbers[i]);
        }
    }
}

Output

10
20
30
40
50

How the Loop Works

For an array of length 5:

i = 0 → numbers[0]
i = 1 → numbers[1]
i = 2 → numbers[2]
i = 3 → numbers[3]
i = 4 → numbers[4]

When:

i = 5

the condition:

i < numbers.length

becomes:

5 < 5

which is false.

Therefore, the loop stops.

Traversing an Array Using Enhanced for Loop

Java also provides the enhanced for loop.

Syntax:

for (dataType variable : array) {
    // statements
}

Example

for (int number : numbers) {
    System.out.println(number);
}

Program 9: Enhanced for Loop

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        for (int number : numbers) {
 
            System.out.println(number);
        }
    }
}

Output

10
20
30
40
50

The enhanced for loop is useful when we need the values but do not need their indexes.

Difference Between for Loop and Enhanced for Loop

Traditional for loop

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

Useful when the index is required.

Enhanced for loop

for (int number : numbers) {
    System.out.println(number);
}

Useful when only the values are required.

Program 10: Display Index and Value

If we want both the index and the value, use a traditional for loop.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40};
 
        for (int i = 0; i < numbers.length; i++) {
 
            System.out.println(
                "Index = " + i + ", Value = " + numbers[i]
            );
        }
    }
}

Output

Index = 0, Value = 10
Index = 1, Value = 20
Index = 2, Value = 30
Index = 3, Value = 40

Default Values of an Array

When an array is created using new, Java automatically initializes its elements with default values.

Example

int[] numbers = new int[3];

Initially:

0  0  0

For a boolean array:

boolean[] flags = new boolean[3];

the values are:

false  false  false

For a String array:

String[] names = new String[3];

the values are:

null  null  null

Program 11: Default Values

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = new int[3];
        boolean[] flags = new boolean[3];
        String[] names = new String[3];
 
        System.out.println(numbers[0]);
        System.out.println(flags[0]);
        System.out.println(names[0]);
    }
}

Output

0
false
null

Taking Array Input from the User

We can use the Scanner class to create an array based on user input.

Program 12: Read Array Elements from User

import java.util.Scanner;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter array size: ");
        int size = scanner.nextInt();
 
        int[] numbers = new int[size];
 
        System.out.println("Enter " + size + " numbers:");
 
        for (int i = 0; i < numbers.length; i++) {
 
            numbers[i] = scanner.nextInt();
        }
 
        System.out.println("Array elements:");
 
        for (int number : numbers) {
 
            System.out.println(number);
        }
 
        scanner.close();
    }
}

Example Input

Enter array size: 5
Enter 5 numbers:
10
20
30
40
50

Output

Array elements:
10
20
30
40
50

This is a common pattern for accepting array input:

int[] numbers = new int[size];
 
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = scanner.nextInt();
}

Program 13: Find the Sum of Array Elements

We can calculate the sum by adding each element to a variable.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        int sum = 0;
 
        for (int number : numbers) {
 
            sum = sum + number;
        }
 
        System.out.println("Sum = " + sum);
    }
}

Output

Sum = 150

The calculation is:

10 + 20 + 30 + 40 + 50 = 150

Program 14: Find the Average

The average can be calculated using:

Average = Sum / Number of Elements

Example

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] marks = {80, 70, 90, 85, 75};
 
        int sum = 0;
 
        for (int mark : marks) {
 
            sum += mark;
        }
 
        double average = (double) sum / marks.length;
 
        System.out.println("Total Marks = " + sum);
        System.out.println("Average Marks = " + average);
    }
}

Output

Total Marks = 400
Average Marks = 80.0

The cast:

(double) sum

ensures that the division can produce a decimal result.

Program 15: Find the Largest Element

We can find the largest element by comparing every element with the current largest value.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {25, 10, 45, 30, 15};
 
        int largest = numbers[0];
 
        for (int i = 1; i < numbers.length; i++) {
 
            if (numbers[i] > largest) {
 
                largest = numbers[i];
            }
        }
 
        System.out.println("Largest = " + largest);
    }
}

Output

Largest = 45

Initially:

largest = numbers[0];

So:

largest = 25

Then the remaining elements are compared with 25.

When 45 is encountered:

45 > 25

so:

largest = 45

Program 16: Find the Smallest Element

The same logic can be used to find the smallest element.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {25, 10, 45, 30, 15};
 
        int smallest = numbers[0];
 
        for (int i = 1; i < numbers.length; i++) {
 
            if (numbers[i] < smallest) {
 
                smallest = numbers[i];
            }
        }
 
        System.out.println("Smallest = " + smallest);
    }
}

Output

Smallest = 10

Program 17: Search for an Element

We can search for an element by comparing the search value with every array element.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        int search = 30;
 
        boolean found = false;
 
        for (int number : numbers) {
 
            if (number == search) {
 
                found = true;
                break;
            }
        }
 
        if (found) {
            System.out.println("Element found");
        } else {
            System.out.println("Element not found");
        }
    }
}

Output

Element found

This is an example of Linear Search because the elements are checked sequentially.

Program 18: Find the Index of an Element

Sometimes we need to know the position of the searched element.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        int search = 40;
 
        int index = -1;
 
        for (int i = 0; i < numbers.length; i++) {
 
            if (numbers[i] == search) {
 
                index = i;
                break;
            }
        }
 
        if (index != -1) {
 
            System.out.println(
                "Element found at index: " + index
            );
 
        } else {
 
            System.out.println("Element not found");
        }
    }
}

Output

Element found at index: 3

We use -1 to represent "not found" because valid array indexes start from 0.

Program 19: Count Even and Odd Numbers

An array can also be used to solve simple data-processing problems.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 15, 20, 25, 30, 35};
 
        int evenCount = 0;
        int oddCount = 0;
 
        for (int number : numbers) {
 
            if (number % 2 == 0) {
 
                evenCount++;
 
            } else {
 
                oddCount++;
            }
        }
 
        System.out.println("Even Numbers = " + evenCount);
        System.out.println("Odd Numbers = " + oddCount);
    }
}

Output

Even Numbers = 3
Odd Numbers = 3

Program 20: Print Only Even Numbers

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 15, 20, 25, 30, 35};
 
        System.out.println("Even Numbers:");
 
        for (int number : numbers) {
 
            if (number % 2 == 0) {
 
                System.out.println(number);
            }
        }
    }
}

Output

Even Numbers:
10
20
30

Program 21: Print Array in Reverse Order

We can traverse the array from the last index to the first index.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        for (int i = numbers.length - 1; i >= 0; i--) {
 
            System.out.println(numbers[i]);
        }
    }
}

Output

50
40
30
20
10

This program prints the elements in reverse order but does not modify the original array.

Program 22: Reverse the Array

If we want to actually reverse the array, we can swap elements from both ends.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        int start = 0;
        int end = numbers.length - 1;
 
        while (start < end) {
 
            int temp = numbers[start];
 
            numbers[start] = numbers[end];
 
            numbers[end] = temp;
 
            start++;
            end--;
        }
 
        System.out.println("Reversed Array:");
 
        for (int number : numbers) {
 
            System.out.println(number);
        }
    }
}

Output

Reversed Array:
50
40
30
20
10

The swapping happens like this:

10  20  30  40  50
↑                 ↑
start             end

After the first swap:

50  20  30  40  10

Then the next pair is swapped:

50  40  30  20  10

Program 23: Sort an Array

Java provides the Arrays utility class to perform common array operations.

We can use:

Arrays.sort()

to sort an array in ascending order.

import java.util.Arrays;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {50, 20, 40, 10, 30};
 
        Arrays.sort(numbers);
 
        System.out.println(Arrays.toString(numbers));
    }
}

Output

[10, 20, 30, 40, 50]

Program 24: Print an Array Using Arrays.toString()

If we write:

System.out.println(numbers);

Java does not provide the elements in the usual array-list format.

Instead, use:

Arrays.toString(numbers)

Example

import java.util.Arrays;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40, 50};
 
        System.out.println(Arrays.toString(numbers));
    }
}

Output

[10, 20, 30, 40, 50]

Program 25: Copy an Array

Java provides Arrays.copyOf() to create a copy of an array.

import java.util.Arrays;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] original = {10, 20, 30, 40, 50};
 
        int[] copy = Arrays.copyOf(
            original,
            original.length
        );
 
        System.out.println("Original: " + Arrays.toString(original));
        System.out.println("Copy: " + Arrays.toString(copy));
    }
}

Output

Original: [10, 20, 30, 40, 50]
Copy: [10, 20, 30, 40, 50]

Program 26: Compare Two Arrays

Using == compares the array references, not the contents.

int[] first = {10, 20, 30};
int[] second = {10, 20, 30};
 
System.out.println(first == second);

Output:

false

To compare the contents, use:

Arrays.equals()

Example

import java.util.Arrays;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] first = {10, 20, 30};
        int[] second = {10, 20, 30};
 
        boolean result = Arrays.equals(first, second);
 
        System.out.println(result);
    }
}

Output

true

Program 27: Pass an Array to a Method

An array can be passed as an argument to a method.

public class HelloWorld {
 
    static void printArray(int[] numbers) {
 
        for (int number : numbers) {
 
            System.out.println(number);
        }
    }
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30, 40};
 
        printArray(numbers);
    }
}

Output

10
20
30
40

The method parameter:

int[] numbers

means that the method accepts an integer array.

Program 28: Return an Array from a Method

A method can also return an array.

public class HelloWorld {
 
    static int[] createArray() {
 
        int[] numbers = {10, 20, 30, 40};
 
        return numbers;
    }
 
    public static void main(String[] args) {
 
        int[] result = createArray();
 
        for (int number : result) {
 
            System.out.println(number);
        }
    }
}

Output

10
20
30
40

The return type:

int[]

indicates that the method returns an integer array.

Program 29: Array of Strings

Arrays can store reference types such as String.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        String[] languages = {
            "Java",
            "Python",
            "C++",
            "JavaScript"
        };
 
        for (String language : languages) {
 
            System.out.println(language);
        }
    }
}

Output

Java
Python
C++
JavaScript

Program 30: Array of Characters

A char array can store individual characters.

public class HelloWorld {
 
    public static void main(String[] args) {
 
        char[] letters = {'J', 'a', 'v', 'a'};
 
        for (char letter : letters) {
 
            System.out.println(letter);
        }
    }
}

Output

J
a
v
a

Program 31: Array of Objects

Arrays can also store references to objects.

Consider a Student class:

class Student {
 
    String name;
 
    Student(String name) {
        this.name = name;
    }
}

We can create an array of Student objects.

class Student {
 
    String name;
 
    Student(String name) {
        this.name = name;
    }
}
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Student[] students = new Student[3];
 
        students[0] = new Student("Amit");
        students[1] = new Student("Priya");
        students[2] = new Student("Rahul");
 
        for (Student student : students) {
 
            System.out.println(student.name);
        }
    }
}

Output

Amit
Priya
Rahul

Here, the array stores references to Student objects.

ArrayIndexOutOfBoundsException

Java throws an ArrayIndexOutOfBoundsException when we try to access an invalid index.

Consider:

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

Valid indexes are:

0
1
2

If we write:

System.out.println(numbers[3]);

index 3 is outside the valid range.

Therefore, Java throws:

ArrayIndexOutOfBoundsException

Program 32: Invalid Array Index

public class HelloWorld {
 
    public static void main(String[] args) {
 
        int[] numbers = {10, 20, 30};
 
        System.out.println(numbers[3]);
    }
}

The program throws an exception because the last valid index is 2.

Remember:

First Index = 0
Last Index = length - 1

Fixed Size of an Array

Once an array is created, its size cannot be changed.

For example:

int[] numbers = new int[5];

The length is permanently:

5

We cannot write:

numbers.length = 10;

This is not allowed.

If the size needs to grow or shrink dynamically, a collection such as ArrayList may be more suitable.

Complete Practical Program

Let's combine several array concepts into one practical program.

The program will:

  1. Read the number of elements.
  2. Read the elements.
  3. Display the array.
  4. Calculate the sum.
  5. Calculate the average.
  6. Find the largest value.
  7. Find the smallest value.
import java.util.Scanner;
import java.util.Arrays;
 
public class HelloWorld {
 
    public static void main(String[] args) {
 
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter number of elements: ");
        int size = scanner.nextInt();
 
        int[] numbers = new int[size];
 
        System.out.println("Enter " + size + " numbers:");
 
        for (int i = 0; i < numbers.length; i++) {
 
            numbers[i] = scanner.nextInt();
        }
 
        int sum = 0;
        int largest = numbers[0];
        int smallest = numbers[0];
 
        for (int number : numbers) {
 
            sum += number;
 
            if (number > largest) {
                largest = number;
            }
 
            if (number < smallest) {
                smallest = number;
            }
        }
 
        double average = (double) sum / numbers.length;
 
        System.out.println();
        System.out.println("Array: " + Arrays.toString(numbers));
        System.out.println("Sum: " + sum);
        System.out.println("Average: " + average);
        System.out.println("Largest: " + largest);
        System.out.println("Smallest: " + smallest);
 
        scanner.close();
    }
}

Example Input

Enter number of elements: 5
Enter 5 numbers:
25
10
45
30
15

Output

Array: [25, 10, 45, 30, 15]
Sum: 125
Average: 25.0
Largest: 45
Smallest: 10

Common Mistakes

Mistake 1: Starting the Index from 1

Incorrect:

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

This can cause an exception because the last valid index is:

numbers.length - 1

Correct:

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

Mistake 2: Using length()

Incorrect:

numbers.length()

Correct:

numbers.length

Mistake 3: Accessing an Invalid Index

For:

int[] numbers = new int[5];

valid indexes are:

0, 1, 2, 3, 4

This is invalid:

numbers[5]

Mistake 4: Assuming Array Size Can Change

Once created:

int[] numbers = new int[5];

the array size remains 5.

An array does not automatically expand when additional elements are needed.

Advantages of Single Dimensional Arrays

1. Simple Structure

Arrays provide a straightforward way to store multiple values.

2. Fast Access

Elements can be accessed directly using their indexes.

numbers[3]

3. Easy Traversal

Arrays can easily be processed using loops.

4. Useful for Fixed-Size Data

Arrays are suitable when the number of elements is known in advance.

5. Supports Primitive Types

Arrays can directly store primitive values such as:

int
double
char
boolean

Limitations of Single Dimensional Arrays

1. Fixed Size

The size cannot be changed after creation.

2. Same Element Type

The elements must be compatible with the array's declared type.

For example:

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

cannot directly contain a String.

3. No Built-In add() or remove()

Arrays do not provide methods such as:

add()
remove()

For dynamically changing collections, classes such as ArrayList can be used.

Array vs ArrayList

FeatureArrayArrayList
SizeFixedDynamic
Index-based accessYesYes
lengthYesNo
size()NoYes
add()NoYes
remove()NoYes
Primitive types directlyYesNo
Collections FrameworkNoYes

Example

int[] numbers = new int[5];

versus:

ArrayList<Integer> numbers = new ArrayList<>();

An array is useful when the size is fixed or known. An ArrayList is useful when the collection needs to grow or shrink dynamically.

Key Points to Remember

  • A Single Dimensional Array stores elements in a single sequence.
  • An array stores elements of the same declared type.
  • Array indexing starts from 0.
  • The first element is at index 0.
  • The last element is at index array.length - 1.
  • Use array[index] to access an element.
  • Use array.length to get the number of elements.
  • An array has a fixed size after creation.
  • Arrays can store primitive values and object references.
  • Use a for loop when the index is required.
  • Use an enhanced for loop when only the values are required.
  • ArrayIndexOutOfBoundsException occurs when an invalid index is accessed.
  • Arrays.toString() can be used to display a one-dimensional array.
  • Arrays.sort() can be used to sort an array.
  • Arrays.equals() can be used to compare array contents.
  • Arrays can be passed to methods and returned from methods.
  • Use ArrayList when a dynamically sized collection is required.

See you in next page....🙂

← OverviewMulti-Dimensional Array →
← OverviewMulti-Dimensional Array →