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 memory management.
For primitive arrays, elements are stored in a continuous memory location,
For non-primitive arrays, references are stored at continuous locations, but the
actual objects may be at different locations in memory.
Key features of Arrays
• Continuous Memory Allocation (for Primitives): Java array elements are
stored in continuous memory locations, which means that the elements are
placed next to each other in memory.
• Zero-based Indexing: The first element of the array is at index 0.
• Fixed Length: Once an array is created, its size is fixed and cannot be
changed.
• Can Store Primitives & Objects: Java arrays can hold both primitive types
(like int, char, Boolean, etc.) and objects (like String, Integer, etc.)
Example: This example demonstrates how to initialize an array and traverse it
using a for loop to print each element.
public class Main {
public static void main(String[] args)
// initializing array
int[] arr = { 1, 2, 3, 4, 5 };
// size of array
1
int n = [Link];
// traversing array
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
}
Basics of Arrays in Java
There are some basic operations we can start with as mentioned below
1. Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
• type: The data type of the array elements (e.g., int, String).
• arrayName: The name of the array.
Note: The array is not yet initialized.
2. Create an Array
To create an array, you need to allocate memory for it using the new keyword:
// Creating an array of 5 integers
int[] numbers = new int[5];
This statement initializes the numbers array to hold 5 integers. The default value
for each element is 0.
2
3. Access an Element of an Array
We can access array elements using their index, which starts from 0:
//Setting the first element of the array
numbers[0] = 10;
// Accessing the first element
int firstElement = numbers[0];
The first line sets the value of the first element to 10. The second line retrieves the
value of the first element.
4. Change an Array Element
To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
5. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = [Link];
Now, we have completed with basic operations so let us go through the in-depth
concepts of Java Arrays, through the diagrams, examples, and explanations.
In-Depth Concepts of Java Array
Following are some important points about Java arrays.
Array Properties
• In Java, all arrays are dynamically allocated.
3
• Arrays may be stored in continuous memory [consecutive memory
locations].
• Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using
size of.
• A Java array variable can also be declared like other variables with [] after
the data type.
• The variables in the array are ordered, and each has an index beginning with
0.
• Java array can also be used as a static field, a local variable, or a method
parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class, depending on the definition of the array. In the case of
primitive data types, the actual values might be stored in continuous memory
locations (JVM does not guarantee this behavior). In the case of class objects, the
actual objects are stored in a heap segment.
Note: This storage of arrays helps us randomly access the elements of an array
[Support Random Access].
4
Creating, Initializing, and Accessing an Arrays in Java
For understanding the array we need to understand how it actually works. To
understand this follow the flow mentioned below:
• Declare
• Initialize
• Access
1. Declaring an Array
The general form of array declaration is
Method:
type var-name[];
Method:
type[] var-name;
The element type determines the data type of each element that comprises the
array. Like an array of integers, we can also create an array of other primitive data
types like char, float, double, etc., or user-defined data types (objects of a class).
2. Initialization an Array in Java
When an array is declared, only a reference of an array is created. The general form
of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number
of elements in the array, and var-name is the name of the array variable that is
linked to the array. To use new to allocate an array, you must specify the type and
number of elements to allocate.
5
Example:
// declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for Boolean), or null (for reference types). Do
refer to default array values in Java.
Obtaining an array is a two-step process. First, you must declare a variable of the
desired array type. Second, you must allocate the memory to hold the array, using
new, and assign it to the array variable. in Java, all arrays are dynamically
allocated.
Array Literal in Java
In a situation where the size of the array and variables of the array are already
known, array literals can be used.
// Declaring array literal
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
• The length of this array determines the length of the created array.
• There is no need to write the new int[] part in the latest versions of Java.
3. Accessing Java Array Elements using for Loop
Now , we have created an Array with or without the values stored in it. Access
becomes an important part to operate over the values mentioned within the array
indexes using the points mentioned below:
• Each element in the array is accessed via its index.
6
• The index begins with 0 and ends at (total array size)-1.
• All the elements of array can be accessed using Java for Loop.
Let us check the syntax of basic for loop to traverse an array:
// Accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : "+ arr[i]);
Implementation:
Java program to illustrate creating an array
of integers, puts some values in the array,
and prints each value to standard output.
class GFG {
public static void main(String[] args)
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the elements of the array
// first to last(fifth) element
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
7
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index "+ i + " : " + arr[i]);
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Types of Arrays in Java
Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in a linear
order.
// A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};
8
2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays (matrices).
A 2D array (matrix)
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
Multidimensional Arrays in Java
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension.
Syntax:
There are 2 methods to declare Java Multidimensional Arrays as mentioned
below:
1:Method
datatype [][] arrayrefvariable;
9
2:Method
datatype arrayrefvariable[][];
Declaration:
// 2D array or matrix
int[][] intArray = new int[10][20];
// 3D array
int[][][] intArray = new int[10][20][10];
One dimensional array examples
1st Example
import [Link];
public class Array1 {
public static void main(String[] args) {
int marks[]={20, 30,40, 50};
for(int x: marks){
[Link](" "+x);
2nd Example
import [Link];
public class Array1 {
public static void main(String[] args) {
Scanner input=new Scanner([Link]);
10
[Link]("Enter number of array element: ");
int num=[Link]();
int mark[]=new int[num];
for(int i=0; i<num; i++){
[Link]("Enter Student Mark: ");
mark[i]=[Link]();
[Link]("Student Marks Are: ");
[Link]("-----------------");
for(int i=0; i<num; i++){
[Link](mark[i]);
3rd Example
import [Link];
public class Array1 {
public static void main(String[] args) {
int total=0;
float percentage=0;
String result;
Scanner input=new Scanner([Link]);
11
[Link]("Enter student name: ");
String sname=[Link]();
[Link]("Enter number of subject: ");
int num=[Link]();
int smark[]=new int[num];
for(int i=0; i<num; i++){
[Link]("Enter "+sname+" marks: ");
smark[i]=[Link]();
total+=smark[i];
[Link]("----------------");
[Link](sname+" total marks are: "+total);
percentage=total/num;
[Link](sname+" percentage is: "+percentage+" %");
if(percentage>55){
[Link](sname+" Congratulation, You are passed");
}else{
[Link]("Sorry, You are failed, Please try again!");
12
Multi dimensional array examples
1st example
public class Array2 {
public static void main(String[] args) {
float marr[][]={{1.1f, 1.2f, 1.3f, 1.4f},
{2.1f, 2.2f, 2.3f, 2.4f},
{3.1f, 3.2f, 3.3f, 3.4f},
{4.1f, 4.2f, 4.3f, 4.4f}};
[Link]("In matrix format");
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
[Link](marr[i][j]+"\t"); }
[Link](); } }
2nd Example
int arr[][]={{10,20,30,40,50},
{60,70,80,90,100},
{110,120,130,140,150},
{160,170,180,190,200}};
[Link]("----- Tow dimensional array-----");
for(int i=0; i<4; i++){
13
for(int j=0; j<4; j++){
[Link](arr[i][j]+"\t");}
[Link]();}
3rd Example
int dept, student, marks;
int total=0;
float percentage=0;
int arr[][][]={{{79,80,90,70},{60,70,75,80}},
{{79,80,90,70},{60,70,75,80}},
{{79,80,90,70},{60,70,75,80}}};
for(dept=0; dept<3; dept++){
[Link]("Department "+(dept+1)+": ");
[Link]("----------------");
for(student=0; student<2; student++){
[Link]("Student "+(student+1)+" Mark: ");
for(marks=0; marks<3; marks++){
[Link](arr[dept][student][marks]+" ");
total=arr[dept][student][marks];
percentage=total/3;}
[Link]("Total "+total+" ");
14
total=0;
[Link]("Percentage : "+percentage+"%");
if(percentage>55){
[Link]("passed");}
else{
[Link]("Failed");}}
[Link]();}
15