0% found this document useful (0 votes)
19 views21 pages

Understanding Java Arrays Basics

Arrays in Java are fundamental data structures that store multiple values of the same type, functioning as objects with unique memory management compared to C/C++. Key features include contiguous memory allocation, zero-based indexing, and the ability to store both primitive types and objects. The document covers array declaration, initialization, accessing elements, and various types of arrays, including single-dimensional and multi-dimensional arrays, along with examples and operations such as passing arrays to methods and returning arrays from methods.

Uploaded by

mr.rakshith005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views21 pages

Understanding Java Arrays Basics

Arrays in Java are fundamental data structures that store multiple values of the same type, functioning as objects with unique memory management compared to C/C++. Key features include contiguous memory allocation, zero-based indexing, and the ability to store both primitive types and objects. The document covers array declaration, initialization, accessing elements, and various types of arrays, including single-dimensional and multi-dimensional arrays, along with examples and operations such as passing arrays to methods and returning arrays from methods.

Uploaded by

mr.rakshith005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Arrays in Java

Last Updated : 28 Mar, 2025

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 contiguous memory location, For non-primitive arrays, references are stored at
contiguous locations, but the actual objects may be at different locations in memory.

Key features of Arrays:

 Contiguous 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

int n = [Link];
// traversing array

for (int i = 0; i < n; i++)

[Link](arr[i] + " ");

Output

12345

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.

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.

 Arrays may be stored in contiguous 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 contiguous 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].

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 1:
type var-name[];

Method 2:
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).

Note: It is just how we can create is an array variable, no actual array exists. It merely tells
the compiler that this variable (int Array) will hold an array of the integer type.

Now, Let us provide memory storage to this created array.

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.

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. Thus, 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.

 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;

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};

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} };

You can also access java arrays using for each loops.

Arrays of Objects in Java

An array of objects is created like an array of primitive-type data items in the following way.

Syntax:
Method 1:
ObjectType[] arrName;

Method 2:
ObjectType arrName[];

Example of Arrays of Objects

Example: Here we are taking a student class and creating an array of Student with five
Student objects stored in the array. The Student objects have to be instantiated using the
constructor of the Student class, and their references should be assigned to the array
elements.

// Java program to illustrate creating

// an array of objects

class Student {

public int roll_no;

public String name;

Student(int roll_no, String name){

this.roll_no = roll_no;

[Link] = name;

public class Main {

public static void main(String[] args){

// declares an Array of Student

Student[] arr;

// allocating memory for 5 objects of type Student.

arr = new Student[5];


// initialize the elements of the array

arr[0] = new Student(1, "aman");

arr[1] = new Student(2, "vaibhav");

arr[2] = new Student(3, "shikar");

arr[3] = new Student(4, "dharmesh");

arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array

for (int i = 0; i < [Link]; i++)

[Link]("Element at " + i + " : { "

+ arr[i].roll_no + " "

+ arr[i].name+" }");

Output

Element at 0 : { 1 aman }

Element at 1 : { 2 vaibhav }

Element at 2 : { 3 shikar }

Element at 3 : { 4 dharmesh }

Element at 4 : { 5 mohit }

Example: An array of objects is also created like

// Java program to illustrate creating

// an array of objects

class Student{

public String name;


Student(String name){

[Link] = name;

@Override

public String toString(){

return name;

public class Main{

public static void main (String[] args){

// declares an Array and initializing the

// elements of the array

Student[] myStudents = new Student[]{

new Student("Dharma"),new Student("sanvi"),

new Student("Rupa"),new Student("Ajay")

};

// accessing the elements of the specified array

for(Student m:myStudents){

[Link](m);

}
Output

Dharma

sanvi

Rupa

Ajay

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed
with an illegal index. The index is either negative or greater than or equal to the size of an
array.

Below code shows what happens if we try to access elements outside the array size:

// Code for showing error "ArrayIndexOutOfBoundsException"

public class GFG {

public static void main(String[] args)

int[] arr = new int[4];

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

[Link](

"Trying to access element outside the size of array");

[Link](arr[5]);

Output
Trying to access element outside the size of array
Exception in thread "main" [Link]: Index 5 out of
bounds for length 4
at [Link]([Link])

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:

// Method 1
datatype [][] arrayrefvariable;

// Method 2
datatype arrayrefvariable[][];

Declaration:

// 2D array or matrix
int[][] intArray = new int[10][20];

// 3D array
int[][][] intArray = new int[10][20][10];

Java Multidimensional Arrays Examples

Example: Let us start with basic two dimensional Array declared and initialized.
// Java Program to demonstrate

// Multidimensional Array

import [Link].*;

class GFG {

public static void main(String[] args){

// Two Dimensional Array

// Declared and Initialized

int[][] arr = new int[3][3];

// Number of Rows

[Link]("Rows : " + [Link]);

// Number of Columns

[Link]("Columns : " + arr[0].length);

Output

Rows:3

Columns:3

Example: Now, after declaring and initializing the array we will check how to Traverse the
Multidimensional Array using for loop.

// Java Program to Multidimensional Array

// Driver Class

public class multiDimensional {


// main function

public static void main(String args[])

// declaring and initializing 2D array

int arr[][] = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++)

[Link](arr[i][j] + " ");

[Link]();

Output

279

361

742

Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, the below program passes
the array to method sum to calculate the sum of the array's values.

// Java program to demonstrate

// passing of array to method

public class Test {

// Driver method

public static void main(String args[])


{

int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1

sum(arr);

public static void sum(int[] arr)

// getting sum of array values

int sum = 0;

for (int i = 0; i < [Link]; i++)

sum += arr[i];

[Link]("sum of array values : " + sum);

Output

sum of array values : 15

Returning Arrays from Methods

As usual, a method can also return an array. For example, the below program returns an
array from method m1.

// Java program to demonstrate

// return of array from method

class Test {
// Driver method

public static void main(String args[])

int arr[] = m1();

for (int i = 0; i < [Link]; i++)

[Link](arr[i] + " ");

public static int[] m1()

// returning array

return new int[] { 1, 2, 3 };

Output

123

Java Array Members

Now, as you know that arrays are objects of a class, and a direct superclass of arrays is a class
Object.

The members of an array type are all of the following:

 The public final field length contains the number of components of the array. Length
may be positive or zero.

 All the members are inherited from class Object; the only method of Object that is
not inherited is its clone method.

 The public method clone() overrides the clone method in class Object and throws
no checked exceptions.

Arrays Types and Their Allowed Element Types


Array Types Allowed Element Types

Any type which can be implicitly promoted


Primitive Type Arrays
to declared type.

Either declared type objects or it's child


Object Type Arrays
class objects.

Abstract Class Type Arrays Its child-class objects are allowed.

Its implementation class objects are


Interface Type Arrays
allowed.

Cloning Arrays in Java

1. Cloning of Single-Dimensional Array

When you clone a single-dimensional array, such as Object[], a shallow copy is performed.
This means that the new array contains references to the original array's elements rather
than copies of the objects themselves. A deep copy occurs only with arrays containing
primitive data types, where the actual values are copied.

Below is the implementation of the above method:


// Java program to demonstrate

// cloning of one-dimensional arrays

class Test {

public static void main(String args[])

int intArray[] = { 1, 2, 3 };

int cloneArray[] = [Link]();

// will print false as shallow copy is created

[Link](intArray == cloneArray);

for (int i = 0; i < [Link]; i++) {

[Link](cloneArray[i] + " ");

Output

false

123

2. Cloning Multidimensional Array

A clone of a multi-dimensional array (like Object[][]) is a "shallow copy," however, which is to


say that it creates only a single new array with each element array a reference to an original
element array, but subarrays are shared.
Below is the implementation of the above method:

// Java program to demonstrate

// cloning of multi-dimensional arrays

class Test {

public static void main(String args[])

int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };

int cloneArray[][] = [Link]();

// will print false

[Link](intArray == cloneArray);

// will print true as shallow copy is created

// i.e. sub-arrays are shared

[Link](intArray[0] == cloneArray[0]);

[Link](intArray[1] == cloneArray[1]);

}
}

Output

false

true

true

Common Operations

The below table demonstrates the common array operations

Operation Example

Sort [Link](arr);

Search [Link](arr, key);

Copy int[] copy = [Link](arr, len);

Fill [Link](arr, 0);

Advantages of Java Arrays

 Efficient Access: Accessing an element by its index is fast and has constant time
complexity, O(1).

 Memory Management: Arrays have fixed size, which makes memory management
straightforward and predictable.

 Data Organization: Arrays help organize data in a structured manner, making it easier
to manage related elements.

Disadvantages of Java Arrays

 Fixed Size: Once an array is created, its size cannot be changed, which can lead to
memory waste if the size is overestimated or insufficient storage if underestimated.

 Type Homogeneity: Arrays can only store elements of the same data type, which
may require additional handling for mixed types of data.
 Insertion and Deletion: Inserting or deleting elements, especially in the middle of an
array, can be costly as it may require shifting elements.

Common Mistakes To Avoid

The common mistakes that can occur when working with arrays in Java are listed below:

 Accessing Out-of-Bounds Index: When we try to access an index that is outside the
range of the array (i.e, negative index or index greater than or equal to the array's
length) it will thrown an index ArrayIndexOutOfBoundsException. Always ensure that
the index is within the bounds, which should be between 0 and [Link] - 1.

 Assuming Array Size Can Change: Java arrays are fixed in size. Attempting to change
the size of an array (like adding or removing elements) is not possible directly.

 Not Initializing Array Elements: If we create an array but do not explicitly initialize its
elements, Java will automatically assign default values based on the type

o For numeric types (e.g., int, double): The default value is 0.

o For boolean arrays: The default value is false.

o For object arrays: The default value is null.

Best Practices

The best practices when working with arrays in Java are listed below:

 Use For-Each Loop When Possible (Avoids Index Errors): The for-each loop is a best
way to iterate over arrays elements without worrying about index-out-of-bounds
errors. It reduces the risk of accessing invalid indices.

 Check Array Length Before Accessing Elements: Always check the length of the array
using [Link] before attempting to access an element. This helps prevent
ArrayIndexOutOfBoundsException.

 Use [Link]() Instead of Manual Copying: If you need to copy an array,


use [Link]() rather than manually copying each element with a loop.

 Prefer ArrayList if Dynamic Resizing is Needed: If you require a collection that can
dynamically resize (add or remove elements), consider using ArrayList instead of an
array.

Common questions

Powered by AI

A 'shallow copy' in Java occurs when cloning an array, resulting in a new array with references to the same objects as the original array. This means that changes made to the objects in the cloned array will affect the objects in the original array. In contrast, a 'deep copy' involves copying the objects themselves, creating entirely independent objects. When using the clone method on single-dimensional arrays, it generates a shallow copy by default, which is generally efficient but can lead to unintended side-effects if the array elements are objects and are modified afterwards . For multidimensional arrays, a shallow copy means that subarrays (array-of-arrays) references are shared between the original and cloned arrays , emphasizing the need for careful consideration when modifying shared references.

To prevent an ArrayIndexOutOfBoundsException in Java, ensure that any index used to access an array element is within the bounds 0 to array.length - 1. This can be achieved by checking the array length before accessing elements, using array.length to guide loops, and preferring for-each loops when only element iteration is needed. These practices help ensure that attempts to access the array do not exceed its allocated size . Additionally, conscientiously code logic to avoid negative indexes or indexes equal to or greater than the length of the array .

Default array values in Java play a crucial role in ensuring uninitialized elements are still valid for operations immediately after memory allocation. For numeric arrays, elements are default-initialized to zero, booleans to false, and reference types to null . This guarantees that every element in a new array is in a predictable state, preventing undefined behavior or errors that might arise from operations on potentially uninitialized elements. Although useful, these default values necessitate caution; relying on them without proper initialization could lead to logic errors, especially when the programmer assumes a different starting value state . As a result, understanding and properly utilizing default values is essential for effective array handling.

Using ArrayList in Java is recommended over arrays when dynamic resizing is necessary due to several advantages. ArrayLists, unlike arrays, automatically resize as elements are added or removed, providing flexibility in managing collections where the size is not predetermined . They also allow storing multiple data types when generics are properly utilized, enabling a more adaptable approach to data storage and manipulation. Operations such as adding, removing, or modifying elements are more efficient and straightforward with ArrayLists, as these actions are cumbersome and computationally expensive with fixed-size arrays that require manual resizing and element shifting . Overall, ArrayList offers enhanced ease of use, flexibility, and efficiency for dynamic data collections.

When passing an array to a method in Java, the reference to the actual array is passed, not a copy of the array itself. This means that any changes made to the array elements within the method will affect the original array outside the method, as both the method and the caller share the same array reference . This behavior reflects Java's treatment of arrays as objects passed by reference, enabling methods to alter the array contents directly, although the reference itself cannot be changed to point to another array within the method . This characteristic can be harnessed for efficient data manipulation but requires careful management to avoid unintended side-effects.

Multidimensional arrays in Java are used to store data in a tabular format resembling matrices with rows and columns. These arrays are essentially arrays of arrays, where each element is a reference to another array. For efficient traversal, nested for loops are typically used, where the outer loop iterates over the rows and the inner loop iterates over each column within a row . For example, a 2D array is traversed using two nested for loops, one for each dimension, to access all elements systematically. This method ensures each element is accessed correctly, facilitating operations like summing elements of each row or finding a specific value efficiently .

In Java, using 'new' to allocate memory for an array is significant because it dynamically allocates space for the specified number of elements of a given type. As a result, each array element is automatically initialized with default values: zero for numeric types, false for boolean types, and null for reference types. This ensures that the array is fully initialized and ready for use, reducing the risk of uninitialized variables . Furthermore, this process allows for the declaration and allocation of arrays in a single step, optimizing initial array setup .

Array literals are particularly useful in scenarios where the array size and initial values are known at compile time. They simplify array initialization by allowing the declaration and instantiation to occur in a single step without needing to explicitly specify the array's size or use the 'new' keyword. This leads to more concise and readable code. In Java, the use of array literals like int[] intArray = {1,2,3}; eliminates the need for specifying the new int[] part, making the process easier and cleaner, especially in applications where the array's content is known and unchanging .

Arrays in Java offer efficient memory management and data organization; however, they come with trade-offs. On the positive side, arrays have a fixed size, ensuring predictable memory allocation and efficient access with constant time complexity (O(1)) for indexed retrieval . This makes them ideal for representing static collections of homogeneous data types where size is known in advance. Conversely, the fixed-size nature of arrays can lead to memory inefficiency if the size is overestimated or program constraints if underestimated. They cannot dynamically resize during runtime, and insertion or deletion operations can be costly as they might require shifting elements . Consequently, while arrays are well-suited for certain tasks, they may not be the optimal choice for collections that require frequent resizing or mixed data types.

Minimizing common mistakes with Java arrays involves several best practices. Firstly, the use of for-each loops is recommended, as they reduce the likelihood of index errors by automatically iterating through all elements . Secondly, always checking array length before accessing its elements can prevent ArrayIndexOutOfBoundsException occurrences . Thirdly, using Arrays.copyOf() is preferred over manual copying for better code readability and reduced error risk . Lastly, considering ArrayList for cases requiring dynamic resizing—as it allows for adding or removing elements without being constrained by fixed size—ensures flexibility and can prevent errors related to array resizing attempts . By adopting these strategies, developers can enhance the reliability and correctness of their array manipulations.

You might also like