Java is a very versatile programming language with many features to make programmers more productive. One of these features is the Java array. Arrays are structures in Java that can store multiple variables of the same type, and they are one of the most commonly used data types in any program.
They provide a way for programmers to organize their code so it is easier to maintain and understand, and they’re also great for sorting out large amounts of data quickly because you can use them as lists or tables with an index number.
Post On: | Java Arrays |
Post Type: | Java Tutorials |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | Software Testingo Telegram Group |
In this post, we will explore how arrays work in Java, what different types of arrays exist, and how you can use them effectively!
What is an Array in Java?
An array is a data type in Java used to store values of the same type, such as integers or strings. Using arrays is a great way to store collections of data, such as a list of people’s names. Rather than storing every person’s name separately, you can put them all in an array and access each name individually with their index number.
This means you can access individual items in an array without knowing their names, sizes, and order. Because it simply doesn’t matter!
As well as making code more organized and easier to understand, arrays also give us performance benefits – we can quickly get the value of a particular array item.
Main features of an array:
- They are fixed size: Array has a maximum capacity, which we cannot change.
- They are indexed: Each item in the array is referenced by an index number (starting from zero).
- The elements within the array are ordered: You can only access items by their position number and not by their names or any other identifying information.
- Occupies contiguous location: Arrays in Java are typically stored in contiguous memory locations, which makes them very fast to access, and this is usually the reason that we store items like arrays.
For example, if you had an array of five integers, they would be stored in memory consecutively, so if a program wanted to get the first element (index number 0), it would read the first memory address; if it then wanted to get the third element (index number 2), it would read the fourth memory location and so on.
Where Can You Use Arrays?
It is worth mentioning that arrays can be used to store values of any type, such as integers, floats, strings, or even custom classes. They can also store multiple values of the same type, which would be called an array of arrays if you were thinking in 3D!
However, even though they can contain different data types, for this post, we will mainly talk about “arrays of integers” simply because they are most commonly used, and the main focus of this post is to help people with Java.
It’s important to note that arrays don’t necessarily have to be used for storing a list of values – they can also be used as lookup tables for mathematical operations and strings.
Advantages of Java Arrays
- Because they are fixed-size, you can use their capacity to store data and work out the maximum size of your array.
- They make code easier to read, understand, and maintain – for example, if we had to add more names to the names array, you would know exactly where in memory you’d need to find them!
- The order in which items in an array are stored means we can access them quickly without writing complex code, saving us time. This is because the computer can go from element 0 to element 1 until it finds the item it wants – such as when we sort an array of numbers and then get the first number.
Disadvantages of Java Arrays
- If we create an array with values that are not used, they can take up unnecessary space in memory and slow down the program execution because we may have to search through empty spaces when looking for them.
- It is easy to make mistakes when working with arrays – for example, mistyping an index number or trying to access it before it has been created.
- The array size can not be changed once a program has started running. For example, if we have an array that can hold five values but continually add more and more, we will eventually reach the limit, and the program will crash.
How to declare an array in Java?
It’s easy to declare an array in Java – write the keyword “Array” followed by the array’s name and then a set of empty square brackets. For example, if we wanted to create an integer array called “prices”, we would write:
int[] prices;
The above line says we are creating and declaring an integer array called prices.
How to Initialize Arrays in Java?
Arrays in Java can be initialized in three different ways:
- Using an initializer list – this is a list of values that we put inside the square brackets when we declare the array. E.g., int[] prices = new int[]{20, 30, 40, 50};.
- Using a constructor, we can create an array where each value is automatically assigned by calling a constructor of the same type (i.e., int).
Program: Write a program to Initialize and Print the Array Elements.
package com.softwaretestingo.array; public class ArrayInitializeUsingConstructorEx { public static int arr[]; public ArrayInitializeUsingConstructorEx(int a[]) { this.arr=a; } public static void main(String[] args) { ArrayInitializeUsingConstructorEx obj=new ArrayInitializeUsingConstructorEx(new int[] {10,20,30,40,50}); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
Output:
10 20 30 40 50
- Using a method called “newInstance” will create a new array and then assign values to each index in the array. You use “new” because arrays must be created like any other object.
How do you access elements of an array in Java?
There are three ways to access elements of an array in Java:
By Index Number: this is the way we used earlier when I mentioned that the first element has an index number of 0, until you get to the last element with an index number equal to (array length – 1). We can then add a value to any of these elements by saying: prices [5] = 100;
Using a for loop: We can use a for loop to go through each value in the array, assigning them to variables before retrieving them and performing operations on them.
for(int i=0; i<prices.length; i++) { System.out.println(prices [I]); }
By using for-each Loop: We can use a for-each loop to automatically assign each value in the array to a variable (e.g., int price), and then we can go through it using that variable, e.g.:
for(int price: prices) { System.out.println(price); }
Different types of Java Arrays
There are four main types of array in Java, which have different uses:
Single Dimension Arrays: this has just one set of values stored in the same place and can be accessed using only one index number. E.g.
int prices[] = {20,30,40,50}; // creates array with 4 elements - prices [0],prices [1] etc int i=prices [0];
Multidimensional Arrays: These are 2D arrays, i.e., they have more than one dimension and can be accessed using two or more indices for each array value. E.g.:
int prices [][] = new int [2][4];
Jagged arrays: A jagged array is similar to a multidimensional array, but the values are not all stored in one place; instead, they can be spread over several other arrays. E.g.:
int [][] prices = new int [2] [5];
Conclusion:
I hope you found this article on arrays to be useful! Understanding how they work and what they can do for your Java program will make it much easier. If you have any questions about the content, please ask in the comment section below.
It would also be great if you could share this article with your friends who are learning Java so they can also learn about arrays! Happy coding!