Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Array Programs in Java

Last Updated on August 21, 2023 by Mayank Dham

An array is a collection of similar types of data. For example, if we need to store the names of 100 different people, we can create an array of the string type that can hold 100 names.
String array[] = new String [100];

The above array is limited to 100 names in this case. The number of values in a Java array is always fixed. We will go over a lot of Array programs in Java to make sure you understand everything.

What is an Array in Java?

An array in Java refers to a collection of variables of the same data type that share a common identifier. Java’s approach to arrays differs from that of C/C++. Here are several important aspects to note regarding Java arrays:

  • In Java, every array is dynamically allocated, unlike C/C++ arrays. This means that memory for arrays is allocated as needed.
  • Arrays are stored in consecutive memory locations, ensuring contiguity.
  • Being objects in Java, arrays possess a property called "length" that reveals their size. This contrasts with C/C++, where the size is determined using "sizeof."
  • Java arrays can be declared using square brackets after the data type, similar to other variable declarations.
  • Array elements are ordered and indexed, starting from 0.
  • Java arrays can serve as static fields, local variables, or method parameters.
  • Array size must be specified using int or short, not long.
  • The immediate parent class of an array type is Object.
  • All array types implement the Cloneable and java.io.Serializable interfaces.

This storage arrangement allows for random access to array elements, supporting efficient random access operations. Once initialized, an array’s size remains fixed and cannot be changed. However, an array reference can be reassigned to point to another array. Arrays can accommodate primitive types (such as int, char) and object references (non-primitives) based on the array’s definition. In the case of primitive types, actual values are stored in contiguous memory locations.

How to Declare an Array in Java?

In Java, here is how we can declare an array.

dataType[] arrayName;

dataType – it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName – it is an identifier

For example,

double[] data;

Here, data is an array that can hold values of type double.

But, how many elements can array this hold?

A good question! In Java, we must allot memory for the array in order to define the maximum number of elements it can contain. For example,

// declare an array
double[] data;

// allocate memory
data = new double[10];

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate the memory of an array in one single statement. For example,

double[] data = new double[10];

How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};

In this case, we’ve made an array named age and initialised it with the values shown in the curly brackets.

Keep in mind that we have not specified the array’s size. Here, the array’s size is automatically determined by the Java compiler by counting the number of elements in the array (i.e. 5).

Each memory region in the Java array has a corresponding number. The value is referred to as an array index. Using the index number, we may initialize arrays in Java as well.
For example,

// declare an array
int[] age = new int[5];

// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..

Elements are stored in the array

Java Arrays initialization

Array indices always start from 0. That is, the first element of an array is at index 0.
If the size of an array is n, then the last element of the array will be at index n-1.

How to Access Elements of an Array in Java?

We can access the element of an array using the index number. Here is the syntax for accessing elements of an array,

// access array elements
array[index]
Let’s see an example of accessing array elements using index numbers.

Example: Access Array Elements

class Main {
 public static void main(String[] args) {
  
   int[] age = {2, 4, 6, 8, 10};

   System.out.println("Accessing Elements of Array:");
   System.out.println("First Element: " + age[0]);
   System.out.println("Second Element: " + age[1]);
   System.out.println("Third Element: " + age[2]);
   System.out.println("Fourth Element: " + age[3]);
   System.out.println("Fifth Element: " + age[4]);
 }
}
Output
Accessing Elements of Array:
First Element: 2
Second Element: 4
Third Element: 6
Fourth Element: 8
Fifth Element: 10

In the above example, notice that we are using the index number to access each element of the array.

We can use loops to access all the elements of the array at once.

Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,

Example: Using For Loop

class Main {
 public static void main(String[] args) {   
   int[] age = {1, 3, 5, 7};
   System.out.println("Using for Loop:");
   for(int i = 0; i < age.length; i++) {
     System.out.println(age[i]);
   }
 }
}
Output
Using for Loop:
1
3
5
7

In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size of the array.

We can also use the for-each loop to iterate through the elements of an array. For example,

Example: Using the for-each Loop

class Main {
 public static void main(String[] args) {  
   int[] age = {12, 8, 4, 2};
   System.out.println("Using for-each Loop:");
   for(int a : age) {
     System.out.println(a);
   }
 }
}
Output
Using for-each Loop:
12
8
4
2

Example: Compute Sum and Average of Array Elements

class Main {
 public static void main(String[] args) {
   int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
   int sum = 0;
   Double average;
   for (int number: numbers) {
     sum += number;
   }  
   int arrayLength = numbers.length;
   average =  ((double)sum / (double)arrayLength);
   System.out.println("Sum = " + sum);
   System.out.println("Average = " + average);
 }
}
Output
Sum = 36
Average = 3.6

In the above example, we have created an array of named numbers. We have used the for…each loop to access each element of the array.

Inside the loop, we are calculating the sum of each element. Notice the line,

int arrayLength = number.length;

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using:

average = ((double)sum / (double)arrayLength);

As you can see, we are converting the int value into double. This is called type casting in Java. To learn more about typecasting, visit Java Type Casting.

Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

double[][] matrix = {{1.2, 4.3, 4.0}, {4.1, -1.1}};

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array.

Conclusion
This article has given a thorough overview of array programs in Java, explaining the fundamental concepts of declaration, initialization, and access. Arrays are efficient data structures for organizing and managing information because they are collections of similar data types. Java arrays differ from C/C++ arrays in several ways, including dynamic allocation, contiguous memory storage, and the "length" property. This article has covered important aspects of array handling, such as declaring and initializing arrays, accessing elements via indices, and using loops to iterate. It also discussed the concept of multidimensional arrays, demonstrating the creation and use of arrays within arrays.

This article provides readers with a solid understanding of array manipulation and utilization by thoroughly exploring the various aspects of arrays in Java. The examples and explanations provided serve as valuable resources for individuals seeking to harness the power of arrays to efficiently manage and process data in their Java programs.

Frequently Asked Questions (FAQs)

Here are some frequently asked questions about Java array programs.
Q1: What is an array in Java and why is it used in programming?
An array in Java is a data structure that holds a fixed number of elements of the same data type in a contiguous memory space. It provides a way to efficiently organize and access a collection of related data. Arrays are used to store and manage data like numbers, strings, or objects and are integral to various algorithms and operations in programming.

Q2: How to declare and initialize an array in Java?
In Java, you can declare an array using the syntax: dataType[] arrayName;, where dataType is the type of elements the array will hold, and arrayName is the identifier for the array. You can also allocate memory and initialize elements using: arrayName = new dataType[size]; or combine declaration and initialization like: dataType[] arrayName = new dataType[size];. Alternatively, arrays can be directly initialized during declaration using curly braces: dataType[] arrayName = {element1, element2, …};.

Q3: How to access elements in a Java array?
Array elements are accessed using their indices. The index of the first element is 0, the second element’s index is 1, and so on. For example, to access the third element in an array named numbers, you would use numbers[2]. Remember that array indices start from 0, so the Nth element is accessed using the index N-1.

Q4: Can you provide an example of iterating through an array in Java?
Certainly! You can use various loops to iterate through an array. One common method is using the for loop with the array’s length property. Here’s an example:

int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

This code snippet iterates through the numbers array and prints each element.

Q5: What are multidimensional arrays, and how are they used in Java?
A multidimensional array in Java is an array of arrays, allowing you to create structures like matrices. You can declare and initialize them using nested curly braces. For example:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

In this example, a matrix is a 2-dimensional array with rows and columns. Accessing elements in a multidimensional array involves specifying both row and column indices, like matrix [rowIndex] [colIndex].

Other Java Programs

Java Program to Add Two Numbers
Java Program to Check Prime Number
Java Program to Check Whether a Number is a Palindrome or Not
Java Program to Find the Factorial of a Number
Java Program to Reverse a Number
Java Program to search an element in a Linked List
Program to convert ArrayList to LinkedList in Java
Java Program to Reverse a linked list
Java Program to search an element in a Linked List
Anagram Program in Java
Inheritance Program in Java
Even Odd Program in Java
Hello World Program in Java
If else Program in Java
Binary Search Program in Java
Linear Search Program in Java
Menu Driven Program in Java
Package Program in Java
Leap Year Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *