Table of contents
1.
Introduction
2.
What is an Array?
3.
Example of a One-Dimensional Array
4.
Organization of a One-Dimensional Array
5.
Basic Operations on One-Dimensional Array
6.
Program on Implementation of One-Dimensional Array in Java
7.
Application of One-Dimensional Array
8.
Frequently Asked Questions
8.1.
Can the size of a one-dimensional array be changed after it is declared?
8.2.
What happens if we try to access an array element using an index that is out of bounds?
8.3.
How do you find the length or size of a one-dimensional array in Java?
9.
Conclusion
Last Updated: Nov 13, 2024
Easy

One Dimensional Array in Java

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Arrays are a fundamental concept in every programming language, including Java, and learning how to use them effectively is very important for any aspiring coder. One of the most basic and essential types of arrays is the one-dimensional array, which allows you to store and manipulate a collection of elements of the same data type in a single, linear structure. A one-dimensional array is a simple list of values, like a series of boxes lined up, each containing a value that can be accessed and manipulated using its index. 

One Dimensional Array in Java

In this article, we will discuss what one-dimensional arrays are, how they work, and their code implementation.

What is an Array?

An array is a data structure that allows you to store a fixed-size collection of elements of the same data type. You can think of an array as a container that holds multiple values, which are arranged in a contiguous block of memory. Each element in the array is assigned a unique index, starting from 0 for the first element and incrementing by 1 for each subsequent element. This index serves as a way to access and manipulate individual elements within the array.

In Java, arrays are objects, and they are created using the "new" keyword followed by the data type and the size of the array enclosed in square brackets. For example, to create an array of integers with a size of 5, you would write:

int[] numbers = new int[5];


This declaration creates an array called "numbers" that can hold 5 integer values. You can then access and modify the elements of the array using their respective indices. For instance, to assign the value 10 to the first element of the array, you would use:

numbers[0] = 10;


Arrays in Java have a fixed size, which means that once an array is created, its size cannot be changed. However, you can create a new array of different sizes and copy the elements from the original array to the new one if needed.

Note: One-dimensional arrays are Java's simplest form of arrays, with elements arranged in a single row or column. They are useful for storing and processing a collection of related data, such as a list of numbers, names, or any other group of values that share the same data type.

Example of a One-Dimensional Array

Let's look at how to declare, initialize, and use a one-dimensional array in Java. 

For example:

int[] ages = new int[5];
ages[0] = 25;
ages[1] = 30;
ages[2] = 35;
ages[3] = 28;
ages[4] = 32;


In this example, we declare an integer array called "ages" with a size of 5. We then initialize each element of the array with specific values using their respective indices.

Alternatively, you can declare and initialize an array in a single line using an array initializer:

String[] names = {"John", "Emily", "Michael", "Sarah", "David"};

 

Here, we create a string array named "names" and initialize it with five-string values. The array size is automatically determined based on the number of elements provided in the initializer.

Once an array is initialized, you can access its elements using the index. For example, to print the value of the third element in the "ages" array, you would use:

System.out.println(ages[2]);


This would output: 35

You can also modify the values of array elements using their indices. For example, to change the value of the fourth element in the "names" array, you can do:

names[3] = "Jessica";


Now, if you print the "names" array, it will output: ["John", "Emily", "Michael", "Jessica", "David"].

One-dimensional arrays in Java provide a simple and efficient way to store and manipulate a collection of values. They allow you to access elements by their indices, making it easy to retrieve or modify specific values within the array.

It's important to note that attempting to access an array element using an index that is out of bounds (i.e., less than 0 or greater than or equal to the array size) will result in an "ArrayIndexOutOfBoundsException". Therefore, it is very important to make sure that you always use valid indices when working with arrays.

Organization of a One-Dimensional Array

When you create a one-dimensional array in Java, it is stored in a contiguous block of memory. This means that each element of the array occupies a consecutive memory location, allowing for efficient access and manipulation of the array elements.

In memory, a one-dimensional array is represented as a sequence of memory cells, where each cell corresponds to an element of the array. The elements are stored in a linear fashion, with the first element at the lowest memory address and the last element at the highest memory address.

For example:

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


In this case, the "numbers" array contains five integer elements. In memory, it would be represented as follows:

[10] [20] [30] [40] [50]
 0    1    2    3    4


Each element occupies a specific memory location, and the array indices correspond to the offset from the starting memory address. The first element, with index 0, is stored at the lowest memory address, and each subsequent element is stored in the next consecutive memory location.

This memory organization allows for efficient random access to any element in the array. When you access an element using its index, such as numbers[3], the Java runtime calculates the memory address of that element by adding the index multiplied by the size of the data type to the starting address of the array. This calculation is performed efficiently, enabling fast retrieval and modification of array elements.

The contiguous memory layout of one-dimensional arrays also enables efficient iteration over the elements. You can use a loop, such as a for loop, to traverse the array from the first element to the last element sequentially. This sequential access pattern is highly optimized and provides excellent performance.

Note: It's important to remember that the size of an array is fixed at the time of creation and cannot be changed dynamically. If you need to resize an array, you typically create a new array with the desired size and copy the elements from the original array to the new one.

Basic Operations on One-Dimensional Array

One-dimensional arrays in Java support various basic operations that allow you to manipulate and work with the elements stored in the array. Let's discuss some of the common operations: 
 

1. Accessing Elements: You can access individual elements of an array using their index. The index starts from 0 for the first element and goes up to (array length - 1) for the last element. For example, to access the third element of an array called "numbers", you would use numbers[2].
 

2. Modifying Elements: You can modify the value of an array element by assigning a new value to it using its index. For example, to change the value of the fourth element in an array called "scores", you can use scores[3] = 85.
 

3. Iterating Over Elements: You can traverse all the elements of an array using a loop. The most common way is to use a for loop starting from index 0 and going up to (array length - 1). 
 

For example:

   int[] numbers = {1, 2, 3, 4, 5};
   for (int i = 0; i < numbers.length; i++) {
       System.out.println(numbers[i]);
   }


This code will print each element of the "numbers" array on a separate line.


4. Finding Array Length: You can determine the length or size of an array using the "length" property. It returns the number of elements in the array. For example, int size = numbers.length; will assign the length of the "numbers" array to the variable "size".


5. Copying Arrays: You can copy the contents of one array to another array using the "System.arraycopy()" method or by manually iterating over the elements and copying them one by one. 


For example : 

   int[] source = {1, 2, 3, 4, 5};
   int[] destination = new int[source.length];
   System.arraycopy(source, 0, destination, 0, source.length);


This code will copy all the elements from the "source" array to the "destination" array.


6. Searching for Elements: You can search for a specific element in an array using a loop and comparing each element with the target value. 


For example : 

   int[] numbers = {10, 20, 30, 40, 50};
   int target = 30;
   int index = -1;
   for (int i = 0; i < numbers.length; i++) {
       if (numbers[i] == target) {
           index = i;
           break;
       }
   }
   if (index != -1) {
       System.out.println("Element found at index: " + index);
   } else {
       System.out.println("Element not found");
   }


This code searches for the value 30 in the "numbers" array and prints its index if found.

Program on Implementation of One-Dimensional Array in Java

In this program, we'll create an array of integers, perform some basic operations on it, and display the results.

public class OneDimensionalArrayExample {
    public static void main(String[] args) {
        // Declare and initialize an array of integers
        int[] numbers = {10, 20, 30, 40, 50};
        
        // Print the original array
        System.out.println("Original Array:");
        printArray(numbers);
        
        // Access and modify an element
        numbers[2] = 35;
        System.out.println("\nModified Array:");
        printArray(numbers);
        
        // Find the length of the array
        int length = numbers.length;
        System.out.println("\nLength of the array: " + length);
        
        // Copy the array to a new array
        int[] copyArray = new int[length];
        System.arraycopy(numbers, 0, copyArray, 0, length);
        System.out.println("\nCopied Array:");
        printArray(copyArray);
        
        // Search for an element in the array
        int target = 40;
        int index = searchElement(numbers, target);
        if (index != -1) {
            System.out.println("\nElement " + target + " found at index: " + index);
        } else {
            System.out.println("\nElement " + target + " not found in the array.");
        }
    }
    
    // Method to print the elements of an array
    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
    
    // Method to search for an element in an array
    public static int searchElement(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Original Array:
10 20 30 40 50 
Modified Array:
10 20 35 40 50 
Length of the array: 5
Copied Array:
10 20 35 40 50 
Element 40 found at index: 3


In this program, we start by declaring and initializing an integer array called `numbers` with five elements. We then print the original array using a custom `printArray()` method that iterates over the array and prints each element.

Next, we access and modify the third element of the array by assigning a new value of 35 to `numbers[2]`. We print the modified array to verify the change.

We find the length of the array using the `length` property and store it in the `length` variable. We then create a new array called `copyArray` with the same length and use `System.arraycopy()` to copy the elements from `numbers` to `copyArray`. We print the copied array to confirm the successful copy operation.

Finally, we search for an element in the array using a custom `searchElement()` method. It takes the array and the target element as parameters and returns the index of the first occurrence of the target element in the array, or -1 if the element is not found. We demonstrate this by searching for the element 40 in the `numbers` array and printing the result.

Note: This program showcases the basic Java operations of declaring, initializing, accessing, modifying, copying, and searching elements in a one-dimensional array. 

Application of One-Dimensional Array

1. Data Storage and Manipulation: Arrays provide a convenient way to store and manipulate data collections. Whether you need to store a list of names, a set of numbers, or any other group of related values, arrays allow you to organize and access the data efficiently. You can perform operations like searching, sorting, filtering, and aggregating data stored in arrays.

 

2. Mathematical Computations: Arrays are often used in mathematical computations and algorithms. For example, you can use arrays to store a series of numbers and perform operations like finding the sum, average, minimum, or maximum value. Arrays can also be used in more complex mathematical algorithms, such as matrix operations, polynomial calculations, and statistical analysis.
 

3. Implementing Data Structures: Arrays are the foundation for many data structures in Java and are used to implement other data structures like stacks, queues, heaps, and hash tables. By using the efficient random access and sequential processing capabilities of arrays, these data structures can provide optimized performance for various operations.
 

4. Algorithm Implementation: Arrays are extensively used to implement various algorithms. Many algorithms, like sorting algorithms (e.g., bubble sort, insertion sort, quicksort), searching algorithms (e.g., linear search, binary search), and dynamic programming algorithms, rely on arrays to store and manipulate data efficiently. Arrays provide a simple and efficient way to represent and process data in these algorithms.
 

5. Input/Output Operations: Arrays can be used to store and process input/output data. For example, you can use arrays to read a list of values from the user or a file and store them for further processing. Similarly, you can use arrays to store the results of computations and write them to an output file or display them to the user.
 

6. Image Processing: In image processing applications, arrays are commonly used to represent and manipulate pixel data. Each pixel of an image can be stored as an element in a one-dimensional array, allowing efficient access and modification of pixel values. Operations like image filtering, resizing, and transformations can be performed using arrays.
 

7. Graphics and Gaming: Arrays are essential in graphics and game development. They store and manipulate game objects, positions, velocities, and other attributes. Arrays can represent game boards, levels, or maps, enabling efficient rendering and game logic implementation. In graphics programming, arrays store vertex data, colors, and other graphical elements.

Frequently Asked Questions

Can the size of a one-dimensional array be changed after it is declared?

No, the size of an array in Java is fixed at the time of declaration and cannot be changed afterward.

What happens if we try to access an array element using an index that is out of bounds?

Accessing an array element with an out-of-bounds index will throw an ArrayIndexOutOfBoundsException.

How do you find the length or size of a one-dimensional array in Java?

You can find the length of an array using the length property, like this: int length = arrayName.length;

Conclusion

In this article, we discussed the concept of one-dimensional arrays in Java. We learned how to declare, initialize, and manipulate arrays using various examples. We also discussed the memory organization of arrays and their applications in different domains. Arrays are a fundamental data structure in Java that provides efficient storage and access to data collections. 

You can also check out our other blogs on Code360.

Live masterclass