0% found this document useful (0 votes)
4 views9 pages

Arrays in Java

The document provides an overview of arrays in Java, explaining their structure, declaration, initialization, and operations such as accessing, updating, and traversing elements. It highlights the differences between primitive and non-primitive arrays, as well as the limitations and advantages of using arrays in Java. Additionally, it covers passing arrays to methods and returning arrays from methods, along with examples to illustrate these concepts.

Uploaded by

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

Arrays in Java

The document provides an overview of arrays in Java, explaining their structure, declaration, initialization, and operations such as accessing, updating, and traversing elements. It highlights the differences between primitive and non-primitive arrays, as well as the limitations and advantages of using arrays in Java. Additionally, it covers passing arrays to methods and returning arrays from methods, along with examples to illustrate these concepts.

Uploaded by

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

6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks

Search... Courses Tutorials Practice Jobs S

Java Tutorial Advanced Java Interview Questions Exercises Examples Quizzes Projects Cheatsheet DSA in Java Java Collection

Share Your Experiences


Basics Arrays in Java Fresher Jobs Experienced Jobs

OOP & Interfaces Last Updated : 8 May, 2026


Python Developer
An array is a collection of elements of the same data type Keylogic Infotech Private Limited
Collections Upto 1 Years • Onsite - Surat (Gujarat)
stored in contiguous memory locations. It allows multiple Apply by Sun Jun 07 2026
Exception Handling
values to be stored under a single name and accessed
Application Support…
Java Advanced using an index. Aress Software
Fresher • Onsite - Nashik (Maharashtra)
Java arrays can hold both primitive types (like int, char, Apply by Sun Jun 07 2026
Practice Java
boolean, etc.) and objects (like String, Integer, etc.)
iOS Engineer
Courses When we use arrays of primitive types, the elements are Keylogic Infotech Private Limited
Upto 2 Years • Onsite - Surat (Gujarat)
stored in contiguous locations. For non primitive types, Apply by Mon Jun 08 2026
Summer SkillUp Explore
references to items are stored at contiguous locations.
View All →
After creating an array, its size is fixed; we can not
change it.
Upcoming Courses
public class Geeks{
MERN Full Stack…
Starting from - June 6, 2026 4.7
public static void main(String[] args){ • LIVE

// Primitive array
Java Backend…
Starting from - June 6, 2026 4.6
int[] arr = {10, 20, 30, 40}; • LIVE
int n = [Link];
DSA & System Desig…
​ Starting from - June 7, 2026 4.9
[Link]("Primitive Array -> "); • LIVE
for (int i = 0; i < n; i++)
View All →
[Link](arr[i] + " ");

[Link]();
​ Trending Posts
// Non-primitive array (String objects)
String[] names = {"Lakshit", "Rahul",
Dr B Padmaja
"Pankaj"}; Vector db vs. Vectorless db Vector DBs store
data as high-dimensional numerical…

[Link]("Non-Primitive Array -> AMAR DEEP
"); Indian IT Companies & Copilot AI Adoption
for (int i = 0; i < [Link]; i++) In the past six months, major Indian IT fir…
[Link](names[i] + " "); Yash Tariyal
} 📘 GFG Connect – Post #146 | Technical
} Series ⚖️ 👉 The Art of Balancing Trade…
Rukaiya
Work Experience Naukri Campus Thrilled
to share my participation in AINCAT 2026…
Output
GOURAV PANDEY
Primitive Array -> 10 20 30 40 Day - 12: The Missing Piece of Recursion
Non-Primitive Array -> Lakshit Rahul Pankaj Backtracking = Recursion + Undo Aur ya…
View All →
Explanation:
The primitive array stores integer values and is
traversed using a loop.
The non-primitive array stores String objects and is
printed in the same way using its length property.

[Link] 1/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks

Primitive Array representation in Java

Non-Primitive Array representation in Java

Declaring an Array
In Java, an array is declared by specifying the data type,
followed by the array name, and empty square brackets [].
Syntax:

dataType[] arrayName;
or
dataType arrayName[];

Initialization an Array
When an array is declared, only a reference is created.
Memory is allocated using the new keyword by specifying
the array size.
Syntax:

int arr[] = new int[size];

Once an array is created, its size is fixed and cannot be


changed. For collections that can grow or shrink
dynamically, Java provides classes like ArrayList or
Vector.
Memory for arrays is always allocated on the heap in
Java.
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).

Initialization using Array Literal

You can use array literals to initialize an array when


declaring it. In this case, the new keyword is not required-

Example:

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

The length of this array determines the length of the


created array.

[Link] 2/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks
There is no need to write the new int[] part in the latest
versions of Java.

initializing-array

Operations on Array Elements

1. Access Array Elements

Elements of an array can be accessed by their position,


called the index. In Java, array indexing starts from 0 (not
1). To access an element, provide the index inside square
brackets [] along with the array name.

class GFG{

public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16};



// Accessing fourth element
[Link](arr[3] + " ");

// Accessing first element
[Link](arr[0]);
}
}

Output

12 2

Note: It is important to note that index cannot be


negative or greater than size of the array minus 1. (0
≤ index ≤ size - 1). Also, it can also be any expression
that results in valid index value.

2. Update Array Elements

To update an element at a specific index in an array, use the


assignment operator = while accessing the array element
and assign a new value.

class GFG{

[Link] 3/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks

public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16};



// Updating first element
arr[0] = 90;
[Link](arr[0]);
}
}

Output

90

3. Traverse Array

Traversing an array means accessing each element one by


one. In Java, arrays can be easily traversed using a loop
where the loop variable runs from 0 to [Link] - 1.

class GFG{

public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16};



// Traversing and printing array
for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
}
}

Output

2 4 8 12 16

Accessing and Updating All Array Elements

4. Size of Array

[Link] 4/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks
The size of an array refers to the number of elements it can
hold. To find the size of array java provides a built-in
property called length.

class GFG{

public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16};


[Link]("Size of array: " +
[Link]);
}
}

Output

Size of array: 5

Arrays of Objects in Java


An array of objects is created like an array of primitive-type
data items

Example: Create an array of five Student objects by


instantiating each Student using its constructor and storing
their references in the array.

class Student {
public int roll_no;
public String name;

Student(int roll_no, String name){


this.roll_no = roll_no;
[Link] = name;
}
}

public class Geeks {
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

[Link] 5/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks

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 }

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.

public class Geeks {


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 si
array");
[Link](arr[5]);
}
}

Output:

Output of elements outside the array size

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.

public class Geeks {


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

[Link] 6/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks

Output

sum of array values : 15

Explanation

This Java program demonstrates how to pass an array to


a method.
An integer array arr is declared and initialized in the
main method.
The sum() method is called with arr as an argument.
Inside the sum() method, all array elements are added
using a for loop.
The final sum is then printed to the console.

Returning Arrays from Methods


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

class Geeks {
// 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 };
}
}

Try It Yourself

Output

1 2 3

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.

Limitations of Java Arrays

[Link] 7/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks
Fixed Size: Array size cannot be changed after creation.
Better option is to use ArrayList (dynamic resizing).
Type Homogeneity: Stores only same data type
elements. Better option is to use Object class,
Collections, or custom classes for mixed data
Costly Insertion & Deletion: Adding/removing elements
requires shifting. Better option is to use LinkedList for
efficient insert/delete operations

Related Posts

Jagged Array in Java


For-each loop in Java
Arrays class in Java

Arrays in Java introduction Visit Course

Suggested Quiz 4 Questions

How do you declare an array in Java?

A int[] arr = new int[5];

B int arr[] = new int(5);

C int arr = new int[5];

D arr[] = new int[5];

View Explanation 1/4 < Previous Next >

Comment N Nitsdheerendra 1.08k

Article Tags: Java java-basics Java-Arrays

Company Explore Tutorials Courses Preparation


About Us POTD Corner

[Link] 8/9
6/4/26, 12:00 PM Arrays in Java - GeeksforGeeks
Corporate & Communications Address: Legal Practice Programming ML and Data Interview
Privacy Policy Problems Languages Science Corner
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Careers Connect DSA DSA and Aptitude
Pradesh (201305) Contact Us Blogs Web Placements Puzzles
Corporate Upskill Technology Web GfG 160
Registered Address:
Solution Courses AI, ML & Data Development System Design
K 061, Tower K, Gulshan Vivante Campus Science Data Science
Apartment, Sector 137, Noida, Gautam
Training DevOps Programming
Buddh Nagar, Uttar Pradesh, 201305
Program CS Core Languages
Subjects DevOps &
GATE Cloud
School GATE
Subjects MongoDB
Software and Certifications
Tools

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

[Link] 9/9

You might also like