Array in JAVA
Arrays in Java work differently than they do in C/C++. Following
are some important points about Java arrays.
·
In Java, all arrays are dynamically allocated. (discussed below)
·
We can find their length using the object property length. Where in C/C++, we find length using sizeof.
·
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 from 0.
·
Java array can be also be used as a static field, a local
variable, or a method parameter.
·
The size of an
array must be specified by int or short value and not long.
·
The direct superclass of an array type is Object.
·
Every array type implements the interfaces Cloneable and java.io.Serializable.
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 are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment.
Creating, Initializing, and Accessing an Array
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
An array declaration has two components: the
type and the name.
type declares the
element type of the array. 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). Thus, the element type for the
array determines what type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
// an array of references to objects of
// the class MyClass (a class created by
// user)
MyClass myClassArray[];
Object[]
ao, // array of Object
Collection[] ca; // array of Collection
// of unknown type
Although the first declaration establishes
that intArray is an array variable, no actual array exists.
It merely tells the compiler that this variable (intArray) will hold an array
of the integer type. To link intArray with an actual, physical array of
integers, you must allocate one using new and assign
it to intArray.
Instantiating an Array in Java
When an array is declared, only a reference of
an array is created. To create or give memory to the array, you create an array
like this: 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:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining
both statements in one
Note :
1.
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). Refer Default array values in Java
2.
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 a situation where the size of the array and variables of the
array are already known, array literals can be used.
int[]
intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
//
Declaring array literal
·
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.
Accessing Java Array Elements using for Loop
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.
//
accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("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 first elements of the array arr[0] = 10; //
initialize the second elements of the array arr[1] = 20; //so
on... arr[2]
= 30; arr[3]
= 40; arr[4]
= 50; //
accessing the elements of the specified array for (int i
= 0; i < arr.length; i++) System.out.println("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
You can also access java arrays using foreach loops.
Arrays of Objects
An array of objects is created like an array of primitive type
data items in the following way.
Student[]
arr = new Student[7]; //student is a user-defined class
The studentArray contains seven memory spaces each of the size
of student class in which the address of seven Student objects can be stored.
The Student objects have to be instantiated using the constructor of the
Student class, and their references should be assigned to the array elements in
the following way.
Student[] arr = new Student[5];
|
// 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; this.name
= name; } } // Elements of the array are
objects of a class Student. public class GFG { public static
void main (String[] args) { //
declares an Array of integers. Student[]
arr; //
allocating memory for 5 objects of type Student. arr
= new Student[5]; //
initialize the first elements of the array arr[0]
= new Student(1,"aman"); //
initialize the second elements of the array arr[1]
= new Student(2,"vaibhav"); //
so on... 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 < arr.length; i++) System.out.println("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
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 GFG { public static
void main (String[] args) { int[]
arr = new int[2]; arr[0]
= 10; arr[1]
= 20; for
(int i = 0; i <= arr.length; i++) System.out.println(arr[i]); } } |
Runtime error
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2
at GFG.main(File.java:12)
Output
10
20
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per dimension. Examples:
int[][] intArray = new int[10][20];
//a 2D array or matrix
int[][][] intArray = new
int[10][20][10]; //a 3D array
|
public class multiDimensional { 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++) System.out.print(arr[i][j]
+ " "); System.out.println(); } } } |
Output
2 7 9
3 6 1
7 4 2
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 < arr.length; i++) sum+=arr[i]; System.out.println("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 < arr.length; i++) System.out.print(arr[i]+"
"); } public static
int[] m1() { //
returning array return
new int[]{1,2,3}; } } |
Output
1 2 3
Class Objects for Arrays
Every array has an associated Class object, shared with all
other arrays with the same component type.
|
// Java program to demonstrate // Class Objects for Arrays class Test { public static
void main(String args[]) { int
intArray[] = new int[3]; byte
byteArray[] = new byte[3]; short
shortsArray[] = new short[3]; //
array of Strings String[]
strArray = new String[3]; System.out.println(intArray.getClass()); System.out.println(intArray.getClass().getSuperclass()); System.out.println(byteArray.getClass()); System.out.println(shortsArray.getClass()); System.out.println(strArray.getClass()); } } |
Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation:
1.
The string “[I” is the run-time type signature for the class
object “array with component type int.”
2.
The only direct superclass of an array type is java.lang.Object.
3.
The string “[B” is the run-time type signature for the class
object “array with component type byte.”
4.
The string “[S” is the run-time type signature for the class
object “array with component type short.”
5.
The string “[L” is the run-time type signature for the class
object “array with component type of a Class.” The Class name is then followed.
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, which
contains the number of components of the array. Length may be positive or zero.
·
All the members inherited from class Object; the only method of
Object that is not inherited is its clone method.
·
The public method clone(), which
overrides the clone method in class Object and throws no checked exceptions.
Arrays Types and Their Allowed Element Types
|
Array
Types |
Allowed
Element Types |
|
Primitive
Type Arrays |
Any type
which can be implicitly promoted to declared type. |
|
Object
Type Arrays |
Either
declared type objects or it’s child class objects. |
|
Abstract
Class Type Arrays |
Its
child-class objects are allowed. |
|
Interface
Type Arrays |
Its
implementation class objects are allowed. |
Cloning of arrays
When you clone a single-dimensional array, such as Object[], a
“deep copy” is performed with the new array containing copies of the original
array’s elements as opposed to references.
|
// Java program to demonstrate // cloning of one-dimensional arrays class Test { public static
void main(String args[]) { int intArray[] = {1,2,3}; int cloneArray[] = intArray.clone(); //
will print false as deep copy is created //
for one-dimensional array System.out.println(intArray == cloneArray); for
(int i = 0; i < cloneArray.length; i++) { System.out.print(cloneArray[i]+"
"); } } } |
Output
false
1 2 3
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.
|
// 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[][] = intArray.clone(); //
will print false System.out.println(intArray == cloneArray); //
will print true as shallow copy is created //
i.e. sub-arrays are shared System.out.println(intArray[0]
== cloneArray[0]); System.out.println(intArray[1]
== cloneArray[1]); } } |
Output
false
true
true
String Array in Java
A String Array is an Array of a fixed number of String values. A
String is a sequence of characters. Generally, a string is an immutable object,
which means the value of the string can not be changed. The String Array works
similarly to other data types of Array.
The main method {Public static void main[ String [] args]; } in
Java is also an String Array.
Consider the below points about the String Array:
- It is an object of the Array.
- It can be declared by the two methods; by specifying the size or without specifying the size.
- It can be initialized either at the time of declaration or by populating the values after the declaration.
- The elements can be added to a String Array after declaring it.
- The String Array can be iterated using the for loop.
- The searching and sorting operation can be performed on the String Array.
Declaration:
The Array declaration is of two types, either we can specify the
size of the Array or without specifying the size of the Array. A String Array
can be declared as follows:
String[]
stringArray1 //Declaration of the
String Array without specifying the size
String[]
stringArray2 = new String[2];
//Declarartion by specifying the size
Another way of declaring the Array is String strArray[], but the
above-specified methods are more efficient and recommended.
Initialization:
The String Array can be initialized easily. Below is the
initialization of the String Array:
String[]
strAr1=new String[] {"Ani", "Sam", "Joe"};
//inline initialization
String[]
strAr2 = {"Ani", "Sam", " Joe"};
String[]
strAr3= new String[3]; //Initialization after declaration with specific
size
strAr3[0]= "Ani";
strAr3[1]= "Sam";
strAr3[2]= "Joe";
All of the above three ways are used to initialize the String
Array and have the same value.
The 3rd method is a specific size method. In this, the value of the
index can be found using the ( arraylength - 1) formula if we want to access
the elements more than the index 2 in the above Array. It will throw the
Java.lang.ArrayIndexOutOfBoundsException exception.
Let's see an example of String Array to demonstrate it's
behavior:
Iteration of String Array
The String Array can be iterated using the for and foreach loop. Consider the below code:
String[] strAr = {"Ani", "Sam",
"Joe"};
for (int i=0; i<StrAr.length; i++)
{
System.out.println(strAr[i]);
}
for ( String str: strAr)
{
Sytem.out.println(str);
}
Adding Elements to a String Array
We can easily add the elements to the String Array just like other data types. It can be done using the following three methods:
- Using Pre-Allocation of the Array
- Using the Array List
- By creating a new Array
Using Pre-Allocation of the Array:
In this method, we already have an Array of larger size. For example, if we require to store the 10 elements, then we will create an Array of size 20. It is the easiest way to expand the Array elements.
Consider the below example to add elements in a pre-allocated
array.
// Java Program to add elements in a pre-allocated Array
import java.util.Arrays;
public class StringArrayDemo {
public static void
main(String[] args) {
String[] sa =
new String[7]; // Creating a new Array of Size 7
sa[0] =
"A"; // Adding Array elements
sa[1] =
"B";
sa[2] =
"C";
sa[3] =
"D";
sa[4] =
"E";
System.out.println("Original Array Elements:" +
Arrays.toString(sa));
int
numberOfItems = 5;
String newItem
= "F"; // Expanding Array Elements Later
String newItem2 ="G";
sa[numberOfItems++] = newItem;
sa[numberOfItems++] = newItem2;
System.out.println("Array after adding two elements:" +
Arrays.toString(sa));
}
}
Output:
Original Array Elements:[A, B, C, D, E, null, null]
Array after adding two elements:[A, B, C, D, E, F, G]
From the above example, we have added two elements in a
pre-allocated Array.
Using ArrayList:
The ArrayList is a fascinating data structure of the Java collection framework. We can easily add elements to a String Array using an ArrayList as an intermediate data structure.
Consider the below example to understand how to add elements to
a String Array using ArrayList:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringArrayDemo1 {
public static void
main(String[] args)
{
// Defining
a String Array
String sa[]
= { "A", "B", "C", "D", "E",
"F" };
//
System.out.println("Initial Array:\n"
+ Arrays.toString(sa));
String ne =
"G"; // Define new element to add
List<String>l = new
ArrayList<String>(
Arrays.asList(sa)); // Convert Array to ArrayList
l.add(ne); //
Add new element in ArrayList l
sa =
l.toArray(sa); // Revert Conversion from ArrayList to Array
// printing
the new Array
System.out.println("Array with added Value: \n"
+ Arrays.toString(sa)) ;
}
}
Output:
Initial Array:
[A, B, C, D, E, F]
Array with added value:
[A, B, C, D, E, F, G]
By Creating a New
Array:
In this method, we will create a new Array with a larger size than the initial Array and accommodate the elements in it. We will copy all the elements to the newly added Array.
Consider the below example:
// Java Program to add elements in a String Array by creating a
new Array
import java.util.Arrays;
public class StringArrayDemo2 {
public static void
main(String[] args) {
//Declaring
Initial Array
String[] sa =
{"A", "B", "C" };
// Printing
the Original Array
System.out.println("Initial Array: " +
Arrays.toString(sa));
int
length_Var = sa.length; //Defining the array length variable
String newElement = "D"; //
Defining new element to add
//define new
array with extended length
String[]
newArray = new String[ length_Var + 1 ];
//Adding all
the elements to initial Array
for (int i=0; i <sa.length; i++)
{
newArray[i] = sa [i];
}
//Specifying
the position of the added elements ( Last)
newArray[newArray.length- 1] = newElement;
//make it
original and print
sa =
newArray;
System.out.println("updated Array: " +
Arrays.toString(sa));
}
}
Output:
Initial Array: [A, B, C]
updated Array: [A, B, C, D]
This is how we can add elements to a String Array. Let's
understand how to search and sort elements in String Array.
Searching in String
Array
For searching a String from the String Array, for loop is used.
Consider the below example:
public class StringArrayExample {
public static void
main(String[] args) {
String[]
strArray = { "Ani", "Sam", "Joe" };
boolean x =
false; //initializing x to false
int in = 0;
//declaration of index variable
String s =
"Sam"; // String to be
searched
// Iteration
of the String Array
for (int i =
0; i < strArray.length; i++) {
if(s.equals(strArray[i])) {
in =
i; x = true; break;
}
}
if(x)
System.out.println(s +" String is found at index "+in);
else
System.out.println(s +" String is not found in the
array");
}
}
Output:
Sam String is found at index 1
In the above example, we have initialized a boolean variable x
to false and an index variable to iterate through the string. Also, we have
declared a local variable String variable s to be searched. Here, the break
keyword will exit the loop as soon as the string is found.
Sorting in String
Array
The sorting in the String array is quite easy. It is performed
like in a traditional array. We use a sort() method to sort the Array elements.
Sorting is easier than searching.
Consider the below example to sort a String Array:
//Java Program to sort elements in a String Array
import java.util.Arrays;
public class StringArraySorting {
public static void
main(String[] args)
{
// Adding
String values
String[] colors
=
{"Cricket","Basketball","Football","Badminton","Tennis"};
// Print
Original values
System.out.println("Entered Sports:
"+Arrays.toString(colors));
Arrays.sort(colors); // Sorting Elements
// Print Sorted
Values
System.out.println("Sorted Sports:
"+Arrays.toString(colors));
}
}
Output:
Entered Sports: [Cricket, Basketball, Football, Badminton,
Tennis]
Sorted Sports: [Badminton, Basketball, Cricket, Football,
Tennis]
From the above example, we can see the elements from a String
Array is sorted using the sort() method.
We can also convert String Array to other data structures such
as List, int Array, ArrayList, and more and vice-versa.
Sources:
https://www.geeksforgeeks.org/





