0% found this document useful (0 votes)
93 views

Arrays in Java: Programming Tutorials and Interview Questions

java array

Uploaded by

Supriya Adake
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Arrays in Java: Programming Tutorials and Interview Questions

java array

Uploaded by

Supriya Adake
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

csFundamentals.com
ProgrammingTutorialsandInterviewQuestions

Home
CProgramming
JavaProgramming
DataStructures
WebDevelopment
TechInterview

ArraysinJava
JavaArrayObjects
CreatingandUsingArrays
VariousWaystoCreate
aJavaArray
JavaEmptyArray
AccessingJavaArray
Elements
ForeachLooptoIterate
ThroughArrayElements
ArrayofCharactersisNot
a String
References

JavaArrayObjects
Arrays in Java are dynamically created objects therefore Java arrays are quite
differentfromCandC++thewaytheyarecreated.ElementsinJavaarrayhaveno
individual names instead they are accessed by their indices. In Java, array index
beginswith0hencethefirstelementofanarrayhasindexzero.ThesizeofaJava
array object is fixed at the time of its creation that cannot be changed later
throughoutthescopeoftheobject.BecauseJavaarraysareobjects,theyarecreated
using new operator. When an object is created in Java by using new operator the
identifier holds the reference not the object exactly. Secondly, any identifier that
holdsreferencetoanarraycanalsoholdvaluenull.Third,likeanyobject,anarray
belongstoaclassthatisessentiallyasubclassoftheclassObject,hencedynamically
createdarraysmaybeassignedtovariablesoftypeObject,alsoallmethodsofclass
Objectcanbeinvokedonarrays.However,therearedifferencesbetweenarraysand
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

1/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

otherobjectsthewaytheyarecreatedandused.
It is very important to note that an element of an
Adsby Google
arraycanbeanarray.Iftheelementtypeis Object or JavaArrayLength
Cloneable or java.io.Serializable ,thensomeorallof JavaCode
theelementsmaybearrays,becauseanyarrayobject JavaStringtoInt
canbeassignedtoanyvariableofthesetypes.

CreatingandUsingArrays
As it is said earlier, a Java array variable holds a reference to an array object in
memory. Array object is not created in memory simply by declaring a variable.
Declaration of a Java array variable creates the variable only and allocates no
memory to it. Array objects are created (allocated memory) by using new operator
thatreturnsareferenceofarraythatisfurtherassignedtothedeclaredvariable.
NoteThatJavaallowscreatingarraysof abstract classtypes.Elementsofsuchan
arraycaneitherbenullorinstancesofanysubclassthatisnotitselfabstract.
Let'stakealookatthefollowingexampleJavaarraydeclarationsthosedeclarearray
variablesbutdonotallocatememoryforthem.
int[]arrOfInts;//arrayofintegers

short[][]arrOfShorts;//twodimensionalarrayofshorts

Object[]arrOfObjects;//arrayofObjects

inti,ai[];//scalarioftypeint,andarrayaiofints

For creating a Java array we first create the array in memory by using new then
assign the reference of created array to an array variable. Here is an example
demonstratingcreationofarrays.
/*ArrayCreationDemo.java*/
//DemonstratingcreationofJavaarrayobjects
publicclassArrayCreationDemo
{
publicstaticvoidmain(String[]args)
{
int[]arrOfInts=newint[5];//arrayof5ints
intarrOfInts1[]=newint[5];//anotherarrayof5ints

//arrayof5ints,initializingarrayatthetimeofcreation
intarrOfInts2[]=newint[]{1,2,3,4,5};

//createsarrayof5Objects
Object[]arrOfObjects=newObject[5];
ObjectarrOfObjects1[]=newObject[5];

//createsarrayof5Exceptions
ExceptionarrEx[]=newException[5];
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

2/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

//arrayofshorts,initializingthatatthetimeofcreation.
shortas[]={1,2,3,4,5};
}
}

Above program declares and allocates memory for


Adsby Google
arraysoftypes int , Object , Exception ,and short .Most JavaRun
importantly, you would have observed that the array HowtoJavaProgramming
indexoperator [] thatisusedtodeclareanarraycan JavaProgramClass
appearaspartofthetypeoraspartofthevariable.For
example, int[]arr and intarr[] ,bothdeclareanarrayarroftype int .
Theplacementof [] duringarraydeclarationmakesdifferencewhenyoudeclarea
scalar and an array in the same statement. For an instance, the statement int i,
arr[]; declares i asan int scalar,and arr asan int array.Whereas,thestatement
int[]i,arr; declaresboth i and arr as int arrays.

Onemoreexample,havealookatfollowingdeclarationsandyouwouldunderstand
theroleofplacementofarrayoperator( [] )inarraydeclarationstatements.
int[]arr1,arr2[];
//isequivalentto
intarr1[],arr2[][];

int[]arr3,arr4;
//isequivalentto
intarr3[],arr4[];

VariousWaystoCreateaJavaArray
InJavaprogramminglanguage,therearemorethanonewaystocreateanarray.For
demonstration,anarrayof int elementscanbecreatedinfollowingnumberofways.
int[]arr=newint[5];

intarr[]=newint[5];

/*Infollowingdeclarations,thesizeofarray
*willbedecidedbythecompilerandwillbe
*equaltothenumberofelementssuppliedfor
*initializationofthearray
*/

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

intarr[]={1,2,3,4,5};

intarr[]=newint[]{1,2,3,4,5};

JavaEmptyArray
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

3/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

Javaallowscreatinganarrayofsizezero.IfthenumberofelementsinaJavaarray
is zero, the array is said to be empty. In this case you will not be able to store any
element in the array therefore the array will be empty. Following example
demonstratesthis.
/*EmptyArrayDemo.java*/
//Demonstratingemptyarray
publicclassEmptyArrayDemo
{
publicstaticvoidmain(String[]args)
{
int[]emptyArray=newint[0];

//willprint0,iflengthofarrayisprinted
System.out.println(emptyArray.length);

//willthrowjava.lang.ArrayIndexOutOfBoundsExceptionexception
emptyArray[0]=1;
}
}

Asyoucanseeinthe EmptyArrayDemo.java ,aJavaarrayofsize0canbecreatedbutit


willbeofnousebecauseitcannotcontainanything.Toprintthesizeof emptyArray
inaboveprogramweuse emptyArray.length thatreturnsthetotalsize,zeroofcourse,
of emptyArray .
Everyarraytypehasa public and final field length thatreturnsthesizeofarrayor
the number of elements an array can store. Note that, it is a field named length ,
unliketheinstancemethodnamed length() associatedwith String objects.
You can also create an array of negative size. Your program will be successfully
compiledbythecompilerwithanegativearraysize,butwhenyourunthisprogram
it will throw java.lang.NegativeArraySizeException exception. Following is an
example:
/*NegativeArraySizeDemo.java*/
//Demonstratingnegativesizedarray

publicclassNegativeArraySizeDemo
{
publicstaticvoidmain(String[]args)
{
/*followingdeclarationthrowa
*runtimeexception
*java.lang.NegativeArraySizeException
*/
int[]arr=newint[2];
}
}

OUTPUT
======
D:\>javacNegativeArraySizeDemo.java
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

4/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

D:\>javaNegativeArraySizeDemo
Exceptioninthread"main"java.lang.NegativeArraySizeException
atNegativeArraySizeDemo.main(NegativeArraySizeDemo.java:12)

D:\>

AccessingJavaArrayElements
Array elements in Java and other programming languages are stored sequentially
and they are accessed by their position or index in array. The syntax of an array
accessexpressiongoeshere:
array_reference[index];

Array index begins at zero and goes up to the size of

Adsby Google

the array minus one. An array of size N has indexes JavaProgramClass


from 0 to N1 . While accessing an array the index UseofJavaProgramming
parameterofthearrayaccessexpressionmustevaluate ExceptionExampleJava
to an integer value, using a long value as an array
indexwillresultintocompiletimeerror.Itcouldbean int literal,avariableoftype
byte , short , int , char ,oranexpressionwhichevaluatestoanintegervalue.

Another important point you should keep in mind that the validity of index is
checkedatruntime.Avalidindexmustfallbetween 0 to N1 foranNsizedarray.
Any index value less than 0 and greater than N1 is invalid. An invalid index, if
encountered,throws ArrayIndexOutOfBoundsException exception.

ForeachLooptoIterateThroughArrayElements
Javaarrayelementsareprintedbyiteratingthroughaloop.Since1.5Javaprovides
anadditionalsyntaxofforlooptoiteratethrougharraysandcollections.Itiscalled
enhanced for loop or foreach loop. Use of enhanced for loop is also illustrated in
ControlFlowiterationtutorial.Hereisanexample:
/*EnForArrayDemo.java*/
//Demonstratingaccessingarrayelements
publicclassEnForArrayDemo
{
publicstaticvoidmain(String[]args)
{
int[][]arrTwoD=newint[3][];
arrTwoD[0]=newint[2];
arrTwoD[1]=newint[3];
arrTwoD[2]=newint[4];

for(int[]arr:arrTwoD)
{
for(intelm:arr)
{
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

5/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

System.out.print(elm+"");
}
System.out.println();
}
}
}

OUTPUT
======
00
000
0000

Program EnForArrayDemo.java demonstrates two important points along with


accessing array elements. First, in a two dimensional array of Java, all rows of the
array need not to have identical number of columns. Second, if arrays are not
explicitlyinitializedthentheyareinitializedtodefaultvaluesaccordingtotheirtype
(see Default values of primitive types in Java). Taking second point into
consideration,wehavenotinitializesarray arrTwoD toanyvalue.Sothewholearray
gotinitializedbyzeroes,because arrTwoD isoftypeint.

JavaArrayofCharactersisNota String
Readers, who come from C and C++ background may find the approach, Java
follows to arrays, different because arrays in Java work differently than they do in
C/C++ languages. In the Java programming language, unlike C, array of char and
String are different. Character array in Java is not a String , as well as a String is

alsonotanarrayof char .Alsoneithera String noranarrayof char isterminatedby


\u0000 (theNULcharacter).

A String object is immutable, that is, its contents never change, while an array of
char hasmutableelements.

LastWord
Thistutorialexplainedhowtodeclare,initializeanduseJavaarrays.Javaarraysare
createdasdynamicobjects.Javaalsosupportsemptyarrays,andevennegativesize
arrays, however, empty arrays cannot be used to store elements. Java provides a
specialsyntaxof for loopcalledenhanced for looporforeachtoaccessJavaarray
elements.AlsoJavaarraysarenot String andthesameistrueviceversa.
Hope you have enjoyed reading this tutorial. Please do write us if you have any
suggestion/commentorcomeacrossanyerroronthispage.Thanksforreading!

References
1.JavaLanguageandVirtualMachineSpecifications
2.Arrays:JavaTutorials
3.IntroductiontoProgrammingUsingJavabyDavidJ.Eck
4.CoreJavaVolumeIFundamentals
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

6/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

5.Java:TheCompleteReference,SeventhEdition

http://csfundamentals.com/javaprogramming/javaarrayvariables.php

7/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

2Comments
Recommend

csfundamentals.com

Share

Login

SortbyOldest

Jointhediscussion
guest 2yearsago

howdoyoucreateanarraydynamicallyinjavawhosesizeisdeterminedatrun
time?

Reply Share

csfundamentals.com

Mod >guest 2yearsago

Followinglinkmayhelp:
https://docs.oracle.com/javase...

Reply Share

ALSOONCSFUNDAMENTALS.COM

DifferenceBetweenStaticand
DynamicLinking

CreateCustom404ErrorPageinPHP
andApacheUsing.htaccess

6comments2yearsago

2comments2yearsago

HarshalChaudharisimpleandpoint

Manishthanks.veryclearexplanation

topointexplanation.reallylikeit.

StaticDynamicLinkinginLinuxand
GCC|DLLDynamicLinkingLibrary

JavaArrayClonevsCopy|Shallow
CopyandDeepCopy|Difference

3comments2yearsago

2comments2yearsago

janakiramireddyaThankyou,nice

csfundamentals.com Thanksfor

explanationandihaveadoubtcan'twe
createadynamiclibrariesusing.a

writingYathirigan!Inordertoperform
deepcopycustomObject,youshould

Subscribe

AddDisqustoyoursiteAddDisqusAdd

Privacy

GetFreeTutorialsbyEmail
Email:
Subscribe

http://csfundamentals.com/javaprogramming/javaarrayvariables.php

8/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

AbouttheAuthor
Krishan Kumar is the
main author for cs
fundamentals.com. He is a
software professional (post
graduated from BITSPilani) and loves
writing
technical
articles
programminganddatastructures.

on

Today'sTechNews
BTmust'putitshouseinorder'
MPs
PostedonTuesdayJuly19,2016
MPsstronglycriticisetelecomsgiantBT
inanewreport,whichaccusesitof
"significantlyunderinvesting"in
Openreach,thedivisionresponsiblefor
mostofthecountry'sbroadbandroll
out.
WhatisARMandwhyisitworth
24bn?
PostedonMondayJuly18,2016
ARM'stechnologyisattheheartof
millionsofsmartphonesandtablets
butthecompany'sinventionsareused
http://csfundamentals.com/javaprogramming/javaarrayvariables.php

9/10

7/19/2016

ArraysinJava.DeclareInitializeandUseArraysinJava

widerstill.
WhyGooglewantsyourmedical
records
PostedonMondayJuly18,2016
Googlehasmadeheadlinesforitsforays
intohealthcarebutwhatisitsultimate
goal?
CourtesyBBCNews

Home ContactUs AboutUs WriteForUs RSSFeed


copyright2016csFundamentals.com

http://csfundamentals.com/javaprogramming/javaarrayvariables.php

10/10

You might also like