Page|55
CHAPTER 10: ARRAYS
10.1 PROPERTIES
I nformationstorageisanimportanttaskforprogrammerstoperformintoday'stechnologicallyadvancedworld.
Forlateruse,eachandeveryitemofinformationmustbestoredinthememorylocation.Wealreadyknowwhat
avariableisandhowitstoresdata.Thesameway,dataisstoredusinganarray.However,Arraysareusedto
store multiple values in a single variable, instead of declaring separate variables for each value. It is adata
storagewherewestoreafixedsetofsimilarelements.Forexample,ifwewanttostorethenamesof40students
then we can create an array of the string type that can store 40 names.
ny data type, including primitivetypeslikeinteger,double,andBooleanaswellasobjecttypeslikeString,
A
canbestoredinaJavaarray.Arrayscanalsobemulti-dimensional,meaningthattheycanhavemultiplerows
andcolumns.Anarray'slengthisassignedwhenitinitiallygetsconstructed.Aftercreation,itslengthisfixed
andcannotbechanged.ArraysinJavaareindex-based,thefirstelementofthearrayisstoredatthe0thindex,
the 2nd element is stored on the 1st index and so on.
10.2 DECLARATION, CREATION AND IN
ITIALIZATION
Making an array in a Java program involves three distinct steps:
D
● eclare the array name.
● Create the array.
● Initialize the array values.
Tocreateanarray,anarrayvariableofthedesireddatatypemustbedeclaredfirst.Thefollowingisthegeneral
f orm for declaring an array:
data _type variable name [ ] ;
Here, the data type determines what type of elements will be stored in the array. For example:
int quiz_marks [ ] ;
I ntheabovedeclarationquiz_marksisthenameofthearray.Andthisarraywillstoreonlytheintegertypesof
elements. Althoughthisdeclarationestablishesthefactthatquiz_marksisanarrayvariable,noarrayactually
exists.
Tolinkquiz_markswithanactual,physicalarrayofintegers,wemustallocateoneactualarrayusingthe“new”
eyword and assign it to quiz_marks. “new “ is a special operator that allocates memory for arrays.
k
quiz_marks = new int [5] ;
Now,wehavefinallycreatedtheactualarray.Here,5definesthelengthofthearray.Thatmeansthisarraycan
s tore five elements.
Page|56
his was the descriptive process for declaration and creation of an array. There is another short way for
T
declaring and creating an array. Instead of using two separate lines of codes wecansimplyuseonelinefor
declaration and creation of an array.
int [ ] total_marks = new int [5];
Here,wehavecreatedanintegerarray,whichcanstore5elements.Initiallywhenwecreateanintegerarray,all
the elements of the array remain 0.
Stackisatemporarymemory.afterusingnew,nowthearraywillbeinsertedintoanactualdatastoragememory
c alled heap. Also, the name of the array only refers to the address where the actual array is stored.
Initial elements of the array change according to the data type. According todifferentdatatypearrayinitial
e lements:
Data Default Values
ype
T
Byte
0
Short 0
Int 0
Long 0
Float 0.0
Double 0.0
Boolean false
Char ‘\u0000′ which is the Unicode for
null
String null
Page|57
Object null
Array declaration and creation examples with different data types:
int [ ] a1 = new int [5];
double [] a1 = new double
[5];
float [] a1 = new float [5];
String [] a1 = new String [5];
o sum up, there are two steps involved in constructing an array. First, you must create a variablewiththe
T
specifieddatatype.Second,youmustusethe“new”keywordtoallocatethememoryrequiredtostorethearray
andthenassignthatmemorytothearrayvariable.Afterthatdefaultelementswillbeassignedautomaticallyto
the array according to the data type.
Now,weneedtostoreouractualelements.Therearemultiplewaystoassignvaluesintoanemptyarray.The
eneral code for inserting any element into any specific index of an array is:
g
array_name [index_number] = element
Page|58
ere,atfirst,wedeclaredthearraywithlength4.Wedeclaredthedatatypeintegerthatiswhytheinitialarray
H
is loaded with all 0’s. After that we initiatedtheforloop,wherewestatedi=0.Becausethefirstindexofan
array is 0. Theloopwillstopwhenwereachthelastindexofthearray.Forthatreasonwehavetoknowthe
length of the array. In Java, the array length is the number of elements that an array can hold. There is no
predefined method to obtain the length of an array. We can find the array length in Javabyusingthearray
attribute length. We use this attribute with the array name. In the above example if we write:
[Link]([Link]);
ur program will give us 4 as an output. So, the last index of an array is [Link]-1.
O
In the above diagram, the value of “i” becomes: 0,1,2,3.
So,thefirstindexis0andthelastindexis3whichisthelength-1.Insidetheloopwearetakinginputsfrom
the user and inserting that input into the array index.
arr[i] = [Link]();
Inthisline,arristhenameofthearray,iistheindexnumber.[Link]()istakinginputsfromtheuser.Here,
extInt only takes the integer inputs
n
Page|59
Inthiswaywecantakeinputsfromtheuserandcreateanarray.Therearevariouswaystoinitializethearray
alues. Some of them are given below:
v
Process Description Code
ynamically
D ere, a is the nameofthearray.a[0]meansthe int a [] = new int [3];
H
allocating one first index of that array. sointhefirstindexwe a[0] = 1;
by one insert the element 1 and so on a[1] = 2;
a[2] = 3;
Created array:
t the time of
A e can also insert the elements at the time of int a[] = { 1, 2, 3, 4, 5 };
W
declaration array creation. here at firstwedeclaredthedata
typewhichisint,thenaisthenameofthearray.
Andthenontherightsideoftheequalsigninside Created array:
curly braces we write the elements we want to
insert.
Using loop singfororwhileloopwecanalsoinsertvalues
U int a [] = new int [5];
intoanarray.Here,theloopstartsfrom0,andit for (int i = 0; i < [Link]; i++) {
will continue untilitdoesn'treachthelastindex a[i] = i + 1;
of the array. The length of the array is 5. the }
value of i will be 0,1,2,3,4. Created array:
aking User
T We can insert elements into an array by taking import [Link];
Input ser inputs.
u Scanner sc= new
a[i] = [Link](); Scanner([Link]);
In this line, a is the name of the array, i is the int a[] = new int [5];
index number. [Link]() is taking inputsfrom for (int i = 0; i < 5 ; i++) {
the user. Here, nextInt only takes the integer a[i] = [Link]();
inputs. }
andom value
R J avahasaspecialclasscalledRandom.Firstwe import [Link];
generator needtoimportthatclass.Afterthatwecreatean Random rd = new Random();
object of that class just like a scanner. int a[] = new int [5];
[Link](10). Here, rd is the object name, for (int i = 0; i < 5 ; i++) {
nextInt will generate only integervaluesand10 a[i] = [Link](10);
definestherange.Anyrandomnumbersbetween }
0 to 10 will be inserted into the array.
In this way, we can declare, create and initialize an array in java. For better efficiency practice different
a pproaches with different data types for array initialization.
10.3 ARRAY ITERATION
rraysareusedtostorehomogeneouselements,meaningthesametypeofelements.Tillnowwehavealready
A
learnedwhatanarrayisandhowtodeclare,initializeanarray.Throughoutthisprocesswestoredournecessary
elementsintothearray.Ourtaskisnotonlytostorethevaluesbutalsoweneedtoworkwiththevalues.Here
Page|60
comes the iteration part where we need to access the elements from thearray.Iteratingoveranarraymeans
a ccessing each element of the array one by one.
tring student_name [ ] = {"David", "Jon", "Sam", "Elsa", "Anne"};
S utput:
O
[Link](name[0]); David
upposewehaveanarray namedstudent_name.Wherewestoredthenameofthosestudentswhowerethetop
S
scorersinthemidtermexamination.Nowyouguyswanttoknowthenameofthestudentwhogotthehighest
marks and became first.
[Link](name[0]);
I ndex0containsthehighestscorer.Soinsidetheprintstatementifwewritethearraynamewithindex0.then
theoutputwillshowthehighestscorer'sname.Here,wejustprintedthename.Wecanalsostoreelementsas
separate variables from the array.
tring student_name [ ] = {"David", "Jon", "Sam", "Elsa", "Anne"};
S utput:
O
top_scorer = student_name [0] David
[Link](top_scorer);
Here,wecreatedanewvariablecalledtop_scorerandcopiedanelementfromthearrayinsidethenewvariable.
he element will remain the same in the array, we just copied it and stored that copy inside a new variable.
T
rint the element
P [Link] (array_name [ index_number ] );
S
Copy and print the element Variable_name = array_name [index_number];
[Link] (Variable_name );
ometimes, we need to iterate the whole array insteadofaspecificindex.Therearemultiplewaystoiterate
S
over a wholearray.Mostlyweusealoopforthatprocess.Thefirstindexofanarrayis0soweinitializefor
loop variable i=0.Theniwillcontinueincrementingby1valueuntilitdoesn'treachthelastindexwhichis
array length - 1. Inside the loop we write the print statement for printing the array.
int arr [ ] = {42,-3,31,97,15}; utput:
O
42
f or(int i =0; i< [Link];i++) { -3
[Link](arr[i]) 31
} 97
15
Here, loop variable i works as the index value and i iterate over the array.
e can iterate an array using not only for loop but also while loop and do while loops. As per our convenience
W
and requirements we can use any of the iteration processes.
or
F loop starts from 0, runsuntilitreachesthelastindexwhichis int a [ ] = {5,6,9,8,6};
Loop a rray length-1. i increments by 1. iterate over the whole array.
Page|61
inside the loop, print statement prints the elements. f or (int i = 0; i < [Link];
i++) {
[Link](a[i]);
}
hile
W loop starts from 0, runsuntilitreachesthelastindexwhichis int a [ ] = {5,6,9,8,6};
Loop a rray length-1. int i = 0;
inside the loop, print statement prints the elements and i while (i < [Link]) {
increments by 1. Iterate over the whole array. [Link](a[i]);
i++;
}
o
D heinitialvariableistartsfrom0.insidethedoblockwewrite
T int a [] = {5,6,9,8,6};
While thestatementstobeexecutedwhichisprintingelementsofthe int i = 0;
Loop array. Then we increment i by 1. Thenusingwhilewesetthe do {
value to stop the loop. [Link](a[i]);
i++;
} while (i < [Link]);
10.4 OPERATIONS ON AN ARRAY
everal different operations can be performed on an array. Some examples are given below. For all the
S
examples, we shall use this array:
int arr [] = {55, 66, 7, -2, 9};
Operation Description Code Output
Length Counts totalnumberofelementsinan [Link]([Link]); 5
a rray.
Traverse raversingthroughalltheelementsin f or (int i = 0; i < [Link]; i++) {
T 5
5
the array one byone.Canbeusedto [Link](arr[i]); 66
perform tasks that requirevisitingall } 7
the elements such as printing all the -2
elements. 9
Insertion Adds an element at the given index. int x [] = new int [5]; 0
x [1] = 10; 0
1
[Link](x[1]); 0
for (int i = 0; i < [Link]; i++) { 0
[Link](x[i]); 0
}
Deletion Deletes an element at the given index. a rr [1]= 0; 5
5
for (int i = 0; i < [Link]; i++) { 0
[Link](arr[i]); 7
} -2
9
Update Updates an element at the given a rr [1]= 65; 5
5
index. for (int i = 0; i < [Link]; i++) { 65
[Link](arr[i]); 7
} -2
9
Page|62
opying an
C reate another array with the same int arr2 [] = new int [[Link]];
C 5
5
array length and datatype, and copyallthe for (int i = 0; i < [Link]; i++){ 0
elements to the new array one by one. arr2[i]= arr[i]; 7
} -2
Thememoryaddressesofbotharrays for (int i = 0; i < [Link]; i++) { 9
are different and changing one array [Link](arr2[i]);
does not affect the another. }
10.5 MU
LTIDIMENSIONAL ARRAYS
he arrays we have looked at so far were all one-dimensional arrays (values are only in a row). When we want
T
to represent data in a tabular form (rows and columns), we use multidimensional arrays. These are basically
arrays of arrays, i.e. an array inside another array. The basic format for creating such arrays is-
data_type[1st dimension][2nd dimension][]..[Nth dimension]array_name=new
data_type[size1][size2]….[sizeN];
For example:
int[][][] newArray = new int[10][20][30]; //This is a multidimensional array.
int[][] numbers = { {1, 2, 3, 4}, {5, 6, 7} }; //This is also a multidimensional array.
oaccessormodifyvaluesofamultidimensionalarray,wecanusearrayindexing,justlikepreviousexamples,
T
but instead ofjustoneindex,weusemultipleindexestopointtothelocationofacertainvalue.Forexample
numbers[1][2]represents7, as [1] means the indexof the outer array, and [2] is the index of the inner array.
Example Code Output
/ /To access values. 2
public class Example1 {
public static void main(String[] args) {
int[][] numbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](numbers[0][1]);
}
}
/ /To modify values.
1
public class Example2 { 9
public static void main(String[] args) {
int[][] numbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](numbers[0][0]); //Prints 1.
numbers[0][0] = 9;
[Link](numbers[0][0]); //Prints 9.
}
}
Page|63
10.6 WO
RKSHEET
A. Answer the following theoretical conceptual questions:
1. M ulti-DimensionalArrays:Discusstheconceptofmulti-dimensionalarrays,suchas2Darraysor
matrices. Explain how they are implemented and provide examples of their applications.
2. ArrayIndexing:Explaintheconceptofarrayindexingandhowitisusedtoaccesselementsinan
array. Discuss the starting index convention (0-based or 1-based) in different programming
languages and its implications.
3. Array Memory Allocation: Describe how arrays are stored in memory. Discuss the contiguous
allocation of elements in memory and the impact of this allocation on array access and
performance.
4. Static vs. Dynamic Arrays: Compare static and dynamic arrays. Explainthedifferencebetween
fixed-size arrays and arrays with dynamic memory allocation. Discuss the advantages and
limitations of each approach.
5. Array Resizing: Discuss the challengesassociatedwithresizingarrays,especiallywhentheyare
implemented with static memory allocation. Explain how dynamic arrays address this issue by
dynamically resizing the array as needed.
6. Array Copying and References: Explain how arrays are copied or referenced in different
programming languages. Discuss the implications of shallow copying versus deep copying for
multidimensional arrays or arrays containing mutable objects.
B. Given an array of integers, write a program to find the maximum element in the array.
iven Array 1
G
{5, 2, 8, 3, 9}
Sample Output 2
9
C. Write a function that takes an array of integers as input and returns the sum of all the elements.
iven Array 1
G
{5, 2, 8, 3, 9}
Sample Output 1
27
D. W rite a program that takes an array and a target element as input and printstheindexofthetarget
element in the array. If not found in the array, print “Not Found”.
iven Array 1
G
{5, 2, 8, 3, 9}
8
Sample Output 1
Target element is at index: 2
iven Array 2
G
{5, 2, 8, 3, 9}
18
Sample Output 2
Not Found
E. Given an array of integers, write a program that prints the occurrence of each element in the array.
iven Array 1
G
{5, 3, 5}
Sample Output 1
5 is repeated 2 time(s)
3 is repeated 1 time(s)
Page|64
F. Given two arrays, write a program that prints an array containing the common elements in both arrays.
iven Arrays
G
{5, 2, 8, 3, 9}
{6, 3, 5, 11, 10}
Sample Output 1
{3, 5}
G. G ivenanarraywithduplicateelements,writeaprogramthatremovestheduplicatesandprintsanew
array with unique elements only.
iven Array 1
G
{5, 2, 8, 3, 2}
Sample Output 1
{5, 2, 8, 3}
H. Write a program that takes an array as input and returns a new array with the elements reversed.
iven Array 1
G
{1, 2, 3, 4, 5}
Sample Output 1
{5, 4, 3, 2, 1}