Array in Java
Array in Java
Topperworld.in
Array in java
characters, or objects.
• Arrays in Java are declared with a specific data type, followed by square
©Topperworld
Java Programming
Advantage of Array:
• Easy to use: Arrays are easy to use and implement, making them a
popular choice among programmers.
• Fast access: Arrays provide fast and efficient access to elements based
on their index, which makes them ideal for storing and retrieving data
quickly.
• Memory efficiency: Arrays are memory-efficient, as they store data in
a contiguous block of memory, which makes them ideal for handling
large amounts of data.
• Easy to manipulate: Arrays can be easily manipulated using loops,
making it easy to perform operations on all elements of an array.
Disadvantage of Array:
• Fixed size: Arrays in Java are of fixed size, which means that the size of
the array cannot be changed once it is initialized.
• Lack of flexibility: Arrays cannot be resized dynamically, which means
that if you need to add or remove elements from an array, you need to
create a new array with a different size.
• Inefficient for certain operations: Arrays are inefficient for certain
operations, such as sorting and searching, as these operations can
require a lot of computational power and time to execute.
• Complex data types: Arrays are not suitable for storing complex data
types, such as objects and structures, as they can only store a single
data type.
❖ Types of Array
There are two types of array:
1. Single Dimensional Array
2. Multidimensional Array
©Topperworld
Java Programming
arrayRefVar=new datatype[size];
©Topperworld
Java Programming
Output: 10,20,70,40,50
Output: 33,3,4,5
Example 2:
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.
©Topperworld
Java Programming
There is no need to write the new int[] part in the latest versions of Java.
Output:
©Topperworld
Java Programming
Example 3:
An array of objects is also created like :
Output:
©Topperworld
Java Programming
2. 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.
Syntax to Declare Multidimensional Array in Java:
dataType[][] arrayRefVar;
©Topperworld
Java Programming
123
Output:
245
445
©Topperworld
Java Programming
012
Output:
3456
78
Output: 268
6 8 10
©Topperworld