0% found this document useful (0 votes)
43 views10 pages

Arrays in Java: Programming Tutorials and Interview Questions

java array

Uploaded by

Supriya Adake
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views10 pages

Arrays in Java: Programming Tutorials and Interview Questions

java array

Uploaded by

Supriya Adake
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

7/19/2016

[Link]

[Link]
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++[Link]
individual names instead they are accessed by their indices. In Java, array index
[Link]
array object is fixed at the time of its creation that cannot be changed later
[Link],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
[Link],likeanyobject,anarray
belongstoaclassthatisessentiallyasubclassoftheclassObject,hencedynamically
createdarraysmaybeassignedtovariablesoftypeObject,alsoallmethodsofclass
[Link],therearedifferencesbetweenarraysand
[Link]

1/10

7/19/2016

[Link]

otherobjectsthewaytheyarecreatedandused.
It is very important to note that an element of an
Adsby Google
[Link] Object or JavaArrayLength
Cloneable or [Link] ,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 [Link]
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.
/*[Link]*/
//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];
[Link]

2/10

7/19/2016

[Link]

//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
[Link]
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 [Link],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,[Link]
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
[Link]

3/10

7/19/2016

[Link]

[Link]
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.
/*[Link]*/
//Demonstratingemptyarray
publicclassEmptyArrayDemo
{
publicstaticvoidmain(String[]args)
{
int[]emptyArray=newint[0];

//willprint0,iflengthofarrayisprinted
[Link]([Link]);

//[Link]
emptyArray[0]=1;
}
}

Asyoucanseeinthe [Link] ,aJavaarrayofsize0canbecreatedbutit


[Link] emptyArray
inaboveprogramweuse [Link] 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 [Link] exception. Following is an
example:
/*[Link]*/
//Demonstratingnegativesizedarray

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

OUTPUT
======
D:\>[Link]
[Link]

4/10

7/19/2016

[Link]

D:\>javaNegativeArraySizeDemo
Exceptioninthread"main"[Link]
[Link]([Link])

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
[Link] int literal,avariableoftype
byte , short , int , char ,oranexpressionwhichevaluatestoanintegervalue.

Another important point you should keep in mind that the validity of index is
[Link] 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
[Link]
enhanced for loop or foreach loop. Use of enhanced for loop is also illustrated in
[Link]:
/*[Link]*/
//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)
{
[Link]

5/10

7/19/2016

[Link]

[Link](elm+"");
}
[Link]();
}
}
}

OUTPUT
======
00
000
0000

Program [Link] 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 [Link]
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,[Link]
[Link],andevennegativesize
arrays, however, empty arrays cannot be used to store elements. Java provides a
specialsyntaxof for loopcalledenhanced for looporforeachtoaccessJavaarray
[Link] String andthesameistrueviceversa.
Hope you have enjoyed reading this tutorial. Please do write us if you have any
suggestion/[Link]!

References
[Link]
[Link]:JavaTutorials
[Link]
[Link]
[Link]

6/10

7/19/2016

[Link]

[Link]:TheCompleteReference,SeventhEdition

[Link]

7/10

7/19/2016

[Link]

2Comments
Recommend

[Link]

Share

Login

SortbyOldest

Jointhediscussion
guest 2yearsago

howdoyoucreateanarraydynamicallyinjavawhosesizeisdeterminedatrun
time?

Reply Share

[Link]

Mod >guest 2yearsago

Followinglinkmayhelp:
[Link]

Reply Share

[Link]

DifferenceBetweenStaticand
DynamicLinking

CreateCustom404ErrorPageinPHP
[Link]

6comments2yearsago

2comments2yearsago

HarshalChaudharisimpleandpoint

[Link]

[Link].

StaticDynamicLinkinginLinuxand
GCC|DLLDynamicLinkingLibrary

JavaArrayClonevsCopy|Shallow
CopyandDeepCopy|Difference

3comments2yearsago

2comments2yearsago

janakiramireddyaThankyou,nice

[Link] Thanksfor

explanationandihaveadoubtcan'twe
createadynamiclibrariesusing.a

writingYathirigan!Inordertoperform
deepcopycustomObject,youshould

Subscribe

AddDisqustoyoursiteAddDisqusAdd

Privacy

GetFreeTutorialsbyEmail
Email:
Subscribe

[Link]

8/10

7/19/2016

[Link]

AbouttheAuthor
Krishan Kumar is the
main author for cs
[Link]. 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
[Link]

9/10

7/19/2016

[Link]

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

Home ContactUs AboutUs WriteForUs RSSFeed


[Link]

[Link]

10/10

You might also like