Exploring One Dimensional Array in Java with Example

Updated on July 26, 2024

Article Outline

Ever found yourself with a mess of variables when trying to handle multiple data points in Java? Well, you’re not alone. We’ve all had the hassle of maintaining multiple related values individually, and that can be a real headache.

 

Enter the one-dimensional array in Java.

 

Think about it like a neat row of lockers, in which each one stores a particular value yet is accessed easily by means of a number. That’s the magic of an array: it stores data efficiently and keeps stuff organised. One dimensional array in Java can be quite useful, specifically when we deal with a collection of things that are similar.

 

Let’s see how we can make one dimensional arrays help our coding lives become easier.

Benefits and Applications of Using One Dimensional Array in Java

Why do we care about one dimensional arrays?

 

Here are a few reasons:

 

  • Efficiency: Elements in arrays are stored in contiguous memory locations. This enables fast and efficient data access.
  • Organisation: They help our code stay clean and organised by organising related data into groups.
  • Memory Management: Arrays prevent the waste of memory space by allocating the exact amount needed for our elements.

 

Now, where can we use these arrays?

 

  • Storing scores: Suppose we want to store the scores of individuals in a game. Rather than declaring different variables to catch the scores, we declare an array.
  • Handling user inputs: Collecting multiple user inputs? Store them in an array for easy access.
  • Data Analysis: An array is ideal for storing and manipulating data sets for analysis.

 

Let’s look at an example to make this clear.

 

Suppose we wish to store a list of weekly temperatures. Rather than declaring seven different variables, we declare an array of size 7:

int[] temperatures = {70, 72, 68, 75, 73, 69, 74};

This line of code is extremely useful, as it especially allows us to organise our data much better and makes it easier to manipulate.

 

Also Read: Java Tutorial

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Detailed Explanation of How to Declare and Initialise a One Dimensional Array

Declaring an Array

Declaring a one dimensional array in Java is simple. We start by specifying the data type, followed by square brackets, and then the array name.

 

Here’s the syntax:

dataType[] arrayName;

For instance, if we’re working with integers:

int[] numbers;

Initialising an Array

Next, we need to allocate memory for the array. This is where we define the size of our array (how many elements it will hold). We use the ‘new’ keyword to do this:

numbers = new int[5];

Now, our array numbers can hold five integer values.

Combining Declaration and Initialisation

We can also declare and initialise the one dimensional array in Java in one line:

int[] numbers = new int[5];

Or, if we know the values beforehand, we can initialise them directly:

int[] scores = {85, 90, 78, 88, 76};

Example: Storing User Input in an Array

Let’s make it interactive. We are going to write a program that takes input from the user and will store it in an array. Here is the code:

import java.util.Scanner; public class UserInputArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] userInput = new int[5]; System.out.println("Enter 5 numbers:"); for (int i = 0; i < userInput.length; i++) { System.out.print("Number " + (i + 1) + ": "); userInput[i] = scanner.nextInt(); } System.out.println("You entered:"); for (int number : userInput) { System.out.print(number + " "); } } }

Output:

output

In this example:

  • We declare an array ‘userInput’ to hold five integers.
  • We then prompt the user to enter five numbers, storing each one in the array.
  • Finally, we print out the numbers to confirm the input.

This interactive approach shows the practical use of arrays in handling user input.

Memory Representation and Accessing Elements in a One Dimensional Array

Have you ever wondered how data is stored in a one dimensional array in Java?

 

Picture a row of boxes, each holding a value. Each box has a specific position, known as an index, starting from zero.

 

This is how a one-dimensional array in Java works. The elements are all stored in memory locations which are contiguous, and hence, therefore, any element can easily be reached using its index.

Visualising Memory Representation

Let’s understand it with an example. Suppose we have an array of integers:

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

Here’s how it’s stored in memory:

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

 

Each value can be accessed directly by its index.

Accessing Elements

Accessing elements in an array is very easy. We use the index inside square brackets. This simplicity is what makes arrays so powerful.

 

For example, to access the third element (which is 30):

int thirdElement = numbers[2]; System.out.println("Third Element: " + thirdElement);

Common Operations on One Dimensional Arrays with Examples

Arrays are versatile. We can perform various operations like accessing, inserting, deleting, searching, and sorting elements.

Accessing Elements

Accessing elements is as simple as using their index.

System.out.println("First Element: " + numbers[0]); System.out.println("Last Element: " + numbers[numbers.length - 1]);

Output:

First Element: 10
Last Element: 50

Inserting Elements

Inserting elements requires creating a new array if we want to change the size.

int[] newNumbers = new int[numbers.length + 1]; System.arraycopy(numbers, 0, newNumbers, 0, numbers.length); newNumbers[newNumbers.length - 1] = 60; System.out.println("New Array: " + Arrays.toString(newNumbers));

Output:

New Array: [10, 20, 30, 40, 50, 60]

Deleting Elements

Deleting an element involves shifting the elements. Let’s delete the element at index 1:

for (int i = 1; i < numbers.length - 1; i++) { numbers[i] = numbers[i + 1]; } numbers[numbers.length - 1] = 0; // Set last element to 0 or default value System.out.println("Array after deletion: " + Arrays.toString(numbers));

Output:

Array after deletion: [10, 30, 40, 50, 0]

Searching Elements

We can search for elements using a loop. Here’s a simple linear search:

int target = 30; boolean found = false; for (int number : numbers) { if (number == target) { found = true; break; } } if (found) { System.out.println("Element " + target + " found."); } else { System.out.println("Element " + target + " not found."); }

Output:

Element 30 found.

Sorting Elements

Sorting arrays can be done using Arrays.sort():

Arrays.sort(numbers); System.out.println("Sorted Array: " + Arrays.toString(numbers));

Output:

Sorted Array: [0, 10, 30, 40, 50]

User Interactive Example: Common Operations on One Dimensional Arrays

import java.util.Arrays; import java.util.Scanner; public class ArrayOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] numbers = new int[5]; // Initializing the array with user input System.out.println("Enter 5 numbers:"); for (int i = 0; i < numbers.length; i++) { System.out.print("Number " + (i + 1) + ": "); numbers[i] = scanner.nextInt(); } // Accessing elements System.out.println("nAccessing Elements:"); System.out.println("First Element: " + numbers[0]); System.out.println("Last Element: " + numbers[numbers.length - 1]); // Inserting an element System.out.print("nEnter a number to insert at the end: "); int newElement = scanner.nextInt(); numbers = Arrays.copyOf(numbers, numbers.length + 1); numbers[numbers.length - 1] = newElement; System.out.println("Array after insertion: " + Arrays.toString(numbers)); // Deleting an element System.out.print("nEnter the index of the element to delete: "); int indexToDelete = scanner.nextInt(); for (int i = indexToDelete; i < numbers.length - 1; i++) { numbers[i] = numbers[i + 1]; } numbers = Arrays.copyOf(numbers, numbers.length - 1); System.out.println("Array after deletion: " + Arrays.toString(numbers)); // Searching for an element System.out.print("nEnter a number to search: "); int target = scanner.nextInt(); boolean found = false; for (int number : numbers) { if (number == target) { found = true; break; } } if (found) { System.out.println("Element " + target + " found."); } else { System.out.println("Element " + target + " not found."); } // Sorting the array Arrays.sort(numbers); System.out.println("nSorted Array: " + Arrays.toString(numbers)); } }

Output:

output2

Advanced Usage of One Dimensional Arrays

Arrays are for more than just basic operations. They can handle more advanced tasks, too.

Summing Elements of an Array

Summing elements are common in data analysis. Here’s how to sum all elements:

int sum = 0; for (int number : numbers) { sum += number; } System.out.println("Sum of elements: " + sum);

Finding the Largest Value in an Array

Finding the largest value is useful in many scenarios.

int max = numbers[0]; for (int number : numbers) { if (number > max) { max = number; } } System.out.println("Maximum value: " + max);

User Interaction Example

import java.util.Scanner; import java.util.Arrays; public class ArrayOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] userNumbers = new int[5];   System.out.println("Enter 5 numbers:"); for (int i = 0; i < userNumbers.length; i++) { System.out.print("Number " + (i + 1) + ": "); userNumbers[i] = scanner.nextInt(); } // Sum of elements int sum = 0; for (int number : userNumbers) { sum += number; } // Find maximum value int max = userNumbers[0]; for (int number : userNumbers) { if (number > max) { max = number; } } System.out.println("You entered: " + Arrays.toString(userNumbers)); System.out.println("Sum of elements: " + sum); System.out.println("Maximum value: " + max); } }

Output:

output3

Performance Considerations: Time and Space Complexity of Array Operations

Do you want to improve the efficiency of your code? How does one dimensional array in Java impact performance?

 

When using arrays, understanding time and space complexity is crucial.

Time Complexity

Time complexity measures how the execution time of an operation grows with the size of the input.

 

Here’s a quick overview of common operations on one dimensional arrays:

 

  • Accessing Elements: Constant time, O(1).
    • Example: Retrieving the first element, numbers[0].
  • Inserting Elements: Linear time, O(n).
    • Inserting at the end is O(1) if there’s space, but O(n) if you need to resize.
  • Deleting Elements: Linear time, O(n).
    • Removing an element requires shifting subsequent elements.
  • Searching Elements: Linear time, O(n) for linear search, O(log n) for binary search on sorted arrays.
  • Sorting Elements: O(n log n) for efficient algorithms like Merge Sort or Quick Sort.

Space Complexity

Space complexity measures the amount of memory used by the data structure.

 

For arrays, space complexity is straightforward:

 

  • Space for Array Elements: O(n).
    • An array of size n takes up space proportional to n.
  • Space for Additional Operations: Typically constant, O(1), unless resizing the array.

Conclusion

A one dimensional array in Java is a powerful tool for managing data. We have examined declaring and initialising arrays, common operations applied to arrays, and the performance implications of these operations. Understanding arrays will make your coding journey smoother and more enjoyable. Grasping these concepts will allow any of us to do things like write efficient, organised, and readable code.

FAQs
An array is declared by defining the data type we will store, followed by square brackets and then the name of our array:
int[] numbers;
  • int: 0
  • float: 0.0
  • boolean: false
  • Object references: null
No, the size of an array is fixed when it's created. If we need a larger array, then we create a new one and copy the elements:
int[] oldArray = {1, 2, 3}; int[] newArray = new int[5]; System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
  • ArrayIndexOutOfBoundsException: Ensure the index is within bounds (0 to array.length - 1).
  • NullPointerException: Initialise the array before using it.
  • Incorrect Array Size: Allocate the correct size to avoid wasting memory or resizing frequently.

Updated on July 26, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved