As we discussed earlier, to store values in Java, variables are used. But a single variable can store only one value. What if want to store more than one value? Let's assume, we want to store the average temperature of 20 days. One way is to store this temperature for 20 days in 20 separate variables. It will be a time-consuming process. Moreover, it is error-prone to declare and initialize 20 variables. Here comes the concept of Arrays. Arrays in Java are special kinds of variables that store more than one value of the same type. In this article, we will discuss the basics of Arrays in Java, types of arrays, particularly single dimensional arrays, and accessing values in arrays using Loops, i.e. simple for loop and enhanced for loop.
Arrays in Java are homogeneous data structures. Arrays data store
one or more values of the same type. A specific element in an array is
accessed or stored by its index number. The index always starts at 0. Arrays
offer an easy way for grouping related information.
Simply we can say, Array is used to hold multiple values of the
same type. For example, we want to store roll numbers of 100 students. Instead
of using 100 variables of int type, it is convenient to use a single array of
length 100 of type int.
The below figure depicts an array having 10 elements. Its
first index is 0 and its last index is length-1=9.
They are implemented in Java as objects. It is vital to remember that arrays in Java are actual objects that can be passed
around and treated just like other objects.
Pros and cons of Java Arrays:
Java arrays have both advantages and disadvantages, let us discuss in detail
Pros
ii. Random access: Elements in an array can be accessed directly using their index, which allows for efficient random access. This makes it quick to retrieve elements based on their position.
iii. Efficiency: Java arrays offer good performance for basic operations like access, update, and search. They have a fixed size, which means memory is allocated contiguously, resulting in efficient memory usage.
iv. Compatibility: Arrays are a fundamental data structure in Java and are well-supported by the language and libraries. They can be used in various contexts, including passing parameters to methods and returning values from methods.
Cons:
- i. Fixed-size: Java arrays have a fixed size that is determined at the time of creation. Once an array is created, its size cannot be changed, requiring you to create a new array if you need to add or remove elements.
iii. Overhead for unused space: If you allocate a large array but only use a small portion of it, the unused space still consumes memory. This can be wasteful when dealing with large datasets.
iv. No built-in methods: Java arrays lack built-in methods for common operations like sorting, searching, or filtering elements. Developers need to write custom code or use utility classes from the standard library to perform these tasks.
v. Homogeneous data type: Java arrays can only store elements of the same data type. This limitation can be restrictive when dealing with complex data structures or heterogeneous data.
How to initialize an array in Java
To initialize an array in Java, we can perform three steps:
- Declare
a variable to hold the array.
- Create
a new array object and assign it to the array variable.
- Store things in that array.
i.
Declaring Array Variables
First of all, a variable is declared to create an array.
This variable will hold the elements/values. The data type followed by a bracket
([]) of this array variable will indicate the type of object that the array
will store in it. The bracket indicates that it is not a simple variable but an
array. It is important to note that array in Java can store elements of the same
data type.
Syntax
datatype[] arrayName;
Here are some examples of array variable declarations:
string[] noOfEmployees;
int[] marks;
double[] temparature;
An alternate method of defining an array variable is to put
the brackets after the variable instead of after the type. They are equivalent,
but above discussed form is often much more preferred.
dataType arrayName[];
Again, The following are all typical array variable
declarations with this method:
string difficultWords[];
int score[];
double temperature[];
ii.
Creating Array Object
In the second step, an array object is created with the help
of new keyword and this object is assigned to an array variable. The size of the
array is also specified at this step.
datatype[] arrayReferenceVariable =
new datatype[size];
or
datatype[] arrayReferenceVariable;
arrayReferenceVariable = new datatype[size];
The following statement creates a new array of Strings
with 10 slots (sometimes called elements). When you create a new array object
using new, you must indicate how many slots that array will hold.
String[] names = new String[10];
Arrays store both Java objects and primitive types
such as integers, doubles or booleans, etc.
int[] temperature = new int[99];
When you create an array object using new, all its
indexes are initialized for you (0 for numeric arrays, false for
boolean, '\0' for character arrays, and null for
objects). Once the array is declared, actual values are assigned to the empty
slots in the array.
It is also possible to create an array and initialize its
contents at the same time. Instead of using new to create the new
array object, enclose the elements of the array inside braces, separated by
commas:
String[] playersList={ "Ali",
"Bashir", "Naseem", "Shakeela",
"Nabeela" };
This example creates an array of String objects
named playersList that contains five elements.
iii.
Accessing the Elements of an Array
We access an array element by referring to the index number.
The following statement accesses the value of the second element in the students’
array. It is noted that Array indexes start with 0. [0] is the first
element. [1] is the second element, and so on.
Example
String[] students = {"Saqib", "jameel",
"shakeel", "Mian"};
System.out.println(students[1]);
The output will be:
Jameel
As the array index starts from 0, student[1] means we are trying
to access the second element from the array which is at index 1.
Let us understand it with the following example.
Problem Statement:
Write a program that instantiates an array of size four of
type int. It prompts the user to fill in all the indexes and then print the
elements of the whole array without using any loop.
import java.util.Scanner;
public class TestArray
{
public
static void main(String[] args ){
Scanner
sc=new Scanner(System.in);
//Instantiating
arry of type int of 4 elements
int[]
rollNo = new int[4];
//Getting Input
System.out.println("Getting
Input");
System.out.print("Enter
first number :");
rollNo[0]
= sc.nextInt();
System.out.print("Enter
second number :");
rollNo[1]
= sc.nextInt();
System.out.print("Enter
third number :");
rollNo[2]
= sc.nextInt();
System.out.print("Enter
forth number :");
rollNo[3]
= sc.nextInt();
//Printing
a line space
System.out.println();
//Printing
Array Values
System.out.println("Printing
Output");
System.out.println("First
Number = " + rollNo[0]);
System.out.println("Second
Number = " + rollNo[1]);
System.out.println("Third
Number = " + rollNo[2]);
System.out.println("Forth
Number = " + rollNo[3]);
}
}
The output of above program will be:
Getting Input
Enter first number : 10
Enter second number : 20
Enter third number : 30
Enter forth number : 40
Printing Output
First Number = 10
Second Number = 20
Third Number = 30
Forth Number = 40
Array length property
To find out how many elements our array has at a particular
time, the “length” property is used. It simply returns the length of the array.
This property is used widely with loops to iterate over the given array. In the
following example, the length property will return the length of the students'
array.
Example
String[] students = {"Nazeer", "Bashir",
"Farooq", "Mahmood"};
System.out.println(students.length);
The output will be:
4
Printing an array in Java
If you have a large array, then a loop structure is the best
option to access and print an array in Java .. You can loop through the array
of elements using
- for
loop
- for-each
or enhanced for loop
Let us discuss both in detail.
1. Accessing array elements using For loop
You can use a simple for loop along with
the length property to specify how many times the loop should run.
The following example outputs all elements in the students' array.
Example
String[] students = {"Nazeer", "Bshir",
"Farooq", "Mahmood"};
for (int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
The output will be:
Nazeer
Bashir
Farooq
Mahmood
Explanation:
In the above example, i is initialized as 0, statement
students[i] will print the element at 0 index, then the element at 1 index, and
so on.
2. Accessing array elements using for-each loop
You can also use for-each or enhanced for loop with array
elements. We have studied for-each loop in the previous chapter.
The following example outputs all elements in the bikes array
using for-each loop.
Example
String[] bikes = {"Power", "Honda",
"Yamaha", "Star"};
for (String i : bikes) {
System.out.println(i);
}
The output will be:
Power
Honda
Yamaha
Star
Problem Statement:
Write a program that instantiates an array of 5 strings.
The program takes input using a simple for loop and prints the out using for-each
loop.
import java.util.Scanner;
public class TestLoopsWithArray
{
public
static void main(String[] args ){
Scanner
sc=new Scanner(System.in);
//declaration
and instantiation
String
StudentNames[]=new String[5];
//length is the property of
array
for(int
i=0;i<StudentNames.length;i++){
System.out.println("Enter
Student Name : ");
StudentNames[i]
= sc.nextLine();
}
System.err.println("");
System.err.println("Student
Names are : ");
for(String
item : StudentNames){
System.err.println(item);
}
}
}
The output will be:
Enter Student Name :
Ali
Enter Student Name :
Jameel
Enter Student Name :
Kamal
Enter Student Name :
Aslam
Enter Student Name :
Rafeeq
Student Names are :
Ali
Jameel
Kamal
Aslam
Rafeeq
Problem Statement 3:
Write a program to find the average of numbers using the array.
public class AverageofArray {
public static void main(String[]
args) {
double[] arr
= {19, 12.89, 16.5, 200, 13.7};
double total
= 0;
for(int i=0;
i<arr.length; i++){
total = total + arr[i];
}
/*
arr.length returns the number of elements
*
present in the array
*/
double
average = total / arr.length;
/* This is used
for displaying the formatted output
* if
you give %.4f then the output would have 4 digits
*
after the decimal point.
*/
System.out.format("The
average is: %.3f", average);
}
}
The output will be:
The average is: 52.418
Problem Statement 4: SumofArray.java
Write a program that sums the elements of an array
import java.util.Scanner;
class SumofArray{
public static void main(String args[]){
Scanner scanner = new
Scanner(System.in);
int[] array = new
int[10];
int sum = 0;
System.out.println("Enter
the elements:");
for (int i=0; i<6;
i++)
{
array[i] = scanner.nextInt();
}
for( int num : array) {
sum
= sum+num;
}
System.out.println("Sum
of array elements is:"+sum);
}
}
The output will be
Enter the elements:
1
2
3
4
5
Sum of array elements is:15
Problem Statement
5: LargestElement.java
Write a program to print the largest element in an array.
public class LargestElement {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize max with the
first element of the array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of the
array with the max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in a given array:"+max);
}
}
The output will be
Largest element present in a given array: 75
In this article, We have discussed arrays in Java in detail.
Arrays are lovely data structures to store more than one value of the same
types in Java. Arrays values are called elements and these elements are accessed
with the help of an index. Arrays index always starts from zero in Java. There
is immense usage of Java arrays in real-life programming.