Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods of Creating Arrays
3.
Syntax
4.
Examples
4.1.
Example 1: Creating & populating an array
4.2.
Example 2: Finding the sum of an array
5.
Difference between Array and ArrayList
6.
Frequently Asked Questions
6.1.
Can I change the size of an array after it is created?
6.2.
Are ArrayLists as fast as arrays?
6.3.
How can I choose between using an Array & an ArrayList?
7.
Conclusion
Last Updated: May 22, 2024
Easy

Array vs Arraylist in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java, arrays & ArrayLists are two basic ways to store collections of data. An array is a fixed-size data structure that holds items of the same type, like a row of boxes. An ArrayList is more flexible - it's a resizable array that can grow or shrink as needed.

Array vs Arraylist in Java

In this article, we'll discuss the key differences between arrays & ArrayLists in Java. We'll check out how to create & use them with code examples. This article will clear all your doubts regarding array and arraylist.

Methods of Creating Arrays

In Java, you can create arrays in a couple different ways:

  • Simple fixed-sized arrays
     
  • Dynamically sized arrays

Simple fixed-sized arrays are the most basic. You decide the size of the array when you create it, and that size stays the same. Here's how to declare a simple integer array of size 5:

int[] numbers = new int[5];


This creates an array called "numbers" that can hold 5 integers. You can access each slot using an index, like numbers[0] for the first slot.

Dynamically sized arrays are a bit more flexible. You can create an array without specifying the size right away, then decide the size later based on some variable. For example:

int size = getSize(); // some method that returns an int
String[] names = new String[size];


Here, we're creating a String array called "names", but the size comes from calling a method getSize(). This lets you choose the array size dynamically at runtime.

So in summary, simple fixed-sized arrays are preset, while dynamically sized arrays can adapt their size as needed. Both are very useful in different situations accordingly.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax

The basic syntax for creating an array in Java looks like this:

dataType[] arrayName = new dataType[size];


Here's what each part means:

  • dataType is the type of data the array will hold (like int, String, etc.)
     
  • arrayName is the name you want to give your array
     
  • size is the number of elements the array will hold
     

So for example, to create an array of integers called "numbers" with a size of 10, you would write:

int[] numbers = new int[10];


Once you've created your array, you can access and modify elements using square brackets [] and the index of the element you want. Remember, array indexes start at 0! Here's an example:

// Set the value of the first element to 42
numbers[0] = 42;
// Get the value of the third element
int third = numbers[2];


You can also use a loop to work with all the elements of an array. A common pattern is to use a for loop to go through each index:

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}


This loop starts i at 0 and goes up to (but not including) the length of the "numbers" array. Each time through, it prints out the element at index i.

Examples

Example 1: Creating & populating an array

// Create an array of strings with size 4
String[] fruits = new String[4];
// Populate the array with values
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Orange";
fruits[3] = "Pear";
// Print out the contents of the array
for (int i = 0; i < fruits.length; i++) {
    System.out.println(fruits[i]);
}

Output:

Apple
Banana
Orange
Pear


In this example, we create a String array called "fruits" with a size of 4. We then assign a value to each index of the array. Finally, we use a for loop to print out each element of the array.

Example 2: Finding the sum of an array

// Create an array of integers
int[] numbers = {4, 2, 7, 1, 9};
// Calculate the sum of the array
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}

// Print out the sum
System.out.println("The sum is: " + sum);


Output:

The sum is: 23


Here, we create an integer array called "numbers" and initialize it with some values. We then use a for loop to go through each element and add it to a running total called "sum". After the loop, we print out the final sum.

Difference between Array and ArrayList

ParameterArrayArrayList
SizeFixed size determined at creationDynamic size, can grow or shrink as needed
PerformanceFaster for simple operationsSlower than arrays, but offers more flexibility
SyntaxdataType[] arrayName = new dataType[size]ArrayList<dataType> listName = new ArrayList<>()
Adding ElementsCannot add elements beyond the initial sizeCan add elements using add() method
Removing ElementsCannot remove elementsCan remove elements using remove() method
PrimitivesCan directly store primitives (int, char, etc.)Cannot directly store primitives, needs wrapper classes
IterationCan use loops to iterate (for, while, etc.)Can use loops or Iterator interface
Type-SafetyNot type-safe, can store any type of objectType-safe, ensures all elements are of specified type
Length/Sizelength attribute gives the size of arraysize() method returns the number of elements
ResizingCannot be resized once createdAutomatically resizes itself as ele

As you can see, arrays and ArrayLists have quite a few differences. Arrays are simpler and faster, but are fixed in size. ArrayLists are more flexible and can dynamically change size, but are a bit slower and require more memory.

The choice between using an array or ArrayList largely depends on your specific needs. If you know the exact number of elements and don't need to change the size, an array is a good choice. If you need flexibility in size and don't mind a slight performance hit, an ArrayList is what you should go with.

Frequently Asked Questions

Can I change the size of an array after it is created?

No, you cannot change the size of an array once it's created in Java. If you need a collection that can change size, consider using an ArrayList instead.

Are ArrayLists as fast as arrays?

ArrayLists are generally slower than arrays. This is because ArrayLists need to resize & potentially copy elements to new locations in memory when they grow or shrink. Arrays, having a fixed size, do not have this overhead & allow faster element access.

How can I choose between using an Array & an ArrayList?

Choose an array if you know the number of elements in advance & it won’t change. Arrays are simpler & faster. Choose an ArrayList if your list size needs to change, or you benefit from methods like add() & remove().

Conclusion

In this article, we've learned the main but important differences between arrays & ArrayLists in Java. We've looked at how each is used, their benefits, & limitations, which has given you the idea that which you need to use in your coding projects. By knowing when to use each type, you can optimize your Java applications for both performance & flexibility, that might improve the performance of your application.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass