Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Array getLong() Method in Java
Next article icon

One Dimensional Array in Java

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An array is a type of Data Structure that can store collections of elements. These elements are stored in contiguous memory locations and the it provides efficient access to each element based on the index of the array element.

In this article, we will learn about a one-dimensional array in Java.

What is an Array?

Arrays are commonly used for storing data and manipulating data in programming languages because they offer fast access to the elements based on their indices and provide efficient memory usage.

Syntax:

dataType [ ] arrayName = new dataType [arraySize] ;

Example of a One Dimensional Array

Below is an example of One Dimensional Array:

Java
// Java Program to implement // One-Dimensional Array  // Driver Class public class ArrayExample {       // Main Function     public static void main(String[] args)     {         // Declare and initialize an array of integers         int[] numbers = { 10, 20, 30, 40, 50 };          // Print the elements of the array         System.out.println("Original Array:");         printArray(numbers);          // Accessing elements of the array         System.out.println("\nElement at index 2: " + numbers[2]);            // Output: 30          // Modifying an element of the array         numbers[3] = 45;          // Print the modified array         System.out.println("\nModified Array:");         printArray(numbers);          // Calculating the sum of elements in the array         int sum = calculateSum(numbers);         System.out.println("\nSum of elements in the array: " + sum);           // Output: 145     }      // 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 calculate the sum of elements in an array     public static int calculateSum(int[] arr)     {         int sum = 0;         for (int num : arr) {             sum += num;         }         return sum;     } } 

Output
Original Array:  10 20 30 40 50     Element at index 2: 30    Modified Array:  10 20 30 45 50     Sum of elements in the array: 155  

Organization of a One-Dimensional Array:

In memory, One-dimensional array in Java is the contiguous block of the memory locations allocated to the hold elements of the same data type. Every element occupied a fixed amount fixed amount of the memory, it is determined by data type of array. The elements in the array are stored sequentially in the memory by the one by one.

Let us assume we have an array of the integers int [ ] numbers = new int [5] ;

The memory organization as shown below:
One_D_Array

  • In the above diagram, 10,20,30,40,50 are represents the individual elements of the array.
  • The length of the array is 5. The length of array is count from 1.
  • The index of the array is count from 0.
  • Each element is stored at the specific index starting from the 0 and going up to the [size-1].
  • The memory addresses are allocated for the each element are contiguous, meaning they are adjacent to the each other in the memory.

Basic Operations on One-Dimensional Array:

Basic operations on a one-dimensional array is include the accessing elements, inserting elements, deleting elements, searching for elements and sorting elements. Now we are discussing about every operation with the time complexity and space complexity:

Operations

Description

Complexity

Accessing Elements

Accessing elements in an array involved the retrieving values and stored at a specific index.

Time Complexity: O(1)
Space Complexity:O(1)

Inserting Elements

Inserting an element into array is involved the adding a new value at the specific index or at end of the array. If the array is filled, it will may be required resizing.

Time Complexity:

  • O(1) - If inserting at the end of the array without resizing the array.
  • O(n) - If inserting at the specific index or at the end of array with resizing, where n is the number of the elements in array.

Space Complexity:

  • O(1) - If the array is no need to resize.
  • O(n) - If the array is required to resize, here n is the number of elements of array.

Deleting Elements

Deleting element from an array is involve the removing a value from the specific index and shifting subsequent elements to fill gap in an array.

Time Complexity: O(n)
Space Complexity: O(1)

Searching for Elements

Searching for specific element in an array is involve traversing the array for find the element in an array.

Time Complexity:

  • O(n) - Linear time complexity for the sequential search, the worst-case scenario involved the traversing the entire array.
  • O(log n) - If the array is binary search is used and sorted, where n is the number of the elements in an array.

Space Complexity:

  • O(1) - Constant space complexity as no additional memory is required.

Sorting Elements

Sorting elements in an array is involve arranging the elements in the specific order such as ascending order or descending order.

Time Complexity:

  • O(n^2) - Quadratic time complexity for the inefficient sorting algorithms such as bubble sort or selection sort.
  • O(n log n) - Average time complexity for the efficient sorting algorithms such as merge sort, heap sort or quick sort.

Space Complexity:

  • O(1) - If the sorting algorithm is an in-place algorithm that doesn't require the extra space.
  • O(n) - If the additional space is required for the sorting such as merge sort.

Program on Implementation of One-Dimensional Array in Java

Here is the Java program that demonstrate the implementation of the one-dimensional array and it performs the basic operations like initializing array, accessing elements, inserting elements, deleting elements, searching for elements and sorting elements:

Java
// Java Program to implement // One Dimensional Array import java.util.Arrays;  // Driver Class public class ArrayExample {       // Main Function     public static void main(String[] args)     {         // Initializing an array         int[] numbers = new int[5];          // Inserting elements into the array         numbers[0] = 10;         numbers[1] = 30;         numbers[2] = 20;         numbers[3] = 50;         numbers[4] = 40;          // Accessing elements in the array         System.out.println("Element at index 0: " + numbers[0]);         // Output: 10          System.out.println("Element at index 3: " + numbers[3]);         // Output: 50          // Deleting an element from the array         deleteElement(numbers,2);           // Delete element at index 2          // Printing the array after deletion         System.out.println(             "Array after deleting element at index 2: "             + Arrays.toString(numbers));          // Searching for an element in the array         int searchElement = 30;         int index = searchElement(numbers, searchElement);         if (index != -1) {             System.out.println("Element " + searchElement                                + " found at index "                                + index);         }         else {             System.out.println("Element " + searchElement                                + " not found in the array");         }          // Sorting the array         Arrays.sort(numbers);          // Printing the sorted array         System.out.println("Sorted array: "                            + Arrays.toString(numbers));     }      // Function to delete an element from the array     public static void deleteElement(int[] arr, int index)     {         if (index < 0 || index >= arr.length) {             System.out.println(                 "Invalid index. Element cannot be deleted.");         }         else {             for (int i = index; i < arr.length - 1; i++) {                 arr[i] = arr[i + 1];             }                        arr[arr.length - 1] = 0;                // Set the last element to 0 or default                // value         }     }      // Function to search for an element in the array     public static int searchElement(int[] arr, int element)     {         for (int i = 0; i < arr.length; i++) {             if (arr[i] == element) {                   // Element found, return its index                 return i;              }         }                  // Element not found         return -1;      } } 

Output
Element at index 0: 10  Element at index 3: 50  Array after deleting element at index 2: [10, 30, 50, 40, 0]  Element 30 found at index 1  Sorted array: [0, 10, 30, 40, 50]  

Application of One-Dimensional Array

One-Dimensional arrays are find the applications in the various domains because of its simplicity, efficiency and versatility. Here are the some common applications. They are:

  • Lists and Collections
  • Data Storage and Retrieval
  • Stacks and Queues
  • Matrices and Vectors
  • Dynamic Programming
  • Sorting and Searching Algorithms
  • Graph Algorithms
  • Histograms and Frequency Counting
  • Image Processing
  • Cryptography

Next Article
Array getLong() Method in Java
author
jagan716
Improve
Article Tags :
  • Java
  • Java-DSA
Practice Tags :
  • Java

Similar Reads

  • Java Multi-Dimensional Arrays
    Multidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
    10 min read
  • Array getInt() Method in Java
    The java.lang.reflect.Array.getInt() is an inbuilt method in Java and is used to return an element at the given index from the specified Array as a int. Syntax Array.getInt(Object []array, int index) Parameters: This method accepts two mandatory parameters: array: The object array whose index is to
    3 min read
  • Array to ArrayList Conversion in Java
    In Java, arrays are fixed-sized, whereas ArrayLists are part of the Java collection Framework and are dynamic in nature. Converting an array to an ArrayList is a very common task and there are several ways to achieve it. Methods to Convert Array to an ArrayList1. Using add() Method to Manually add t
    4 min read
  • Read File Into an Array in Java
    In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don't know the exact lines o
    8 min read
  • Array getLong() Method in Java
    The java.lang.reflect.Array.getLong() is an inbuilt method in Java and is used to return an element at the given index from a specified Array as a long. Syntax: Array.getLong(Object []array, int index) Parameters : This method accepts two mandatory parameters: array: The object array whose index is
    3 min read
  • Array getShort() method in Java
    The java.lang.reflect.Array.getShort() is an in-built method of Array class in Java and is used to return the element present at a given index from the specified Array as a short. Syntax: Array.getShort(Object []array,int index) Parameters: array: The object array whose index is to be returned. inde
    3 min read
  • Arrays in Java
    Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
    15+ min read
  • Compare Two Arrays in Java
    In Java, comparing two arrays can be confusing, because the "==" operator only checks if the two arrays point to the same memory location. To compare the contents of arrays, we need to use other methods like Arrays.equals() or Arrays.deepEquals(). Example: Let us see in the below example, how to com
    5 min read
  • Arrays.fill() in Java with Examples
    The Arrays.fill() is a method in the java.util.Arrays class. This method assigns a specified value to each element of an entire array or a specified range within the specified array. Example: Now let's understand this with the below simple example to fill an entire array with a specified value: [GFG
    3 min read
  • ArrayList in Java
    Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences