SlideShare a Scribd company logo
https://www.facebook.com/Oxus20
oxus20@gmail.com
Java
Arrays
Java Arrays
Zalmai Arman
Outline
https://www.facebook.com/Oxus20
Introduction
Array Basics
Copying Arrays
Passing Arrays to Methods
Returning an Array from a Method
(Optional) Variable-Length Argument Lists
The Arrays Class
Two-Dimensional Arrays
(Optional) Multidimensional Arrays
Introduction
Ā» Often you will have to store a large number of values
during the execution of a program.
Ā» Suppose, for instance, that you want to read one hundred
numbers, compute their average, and find out how many
numbers are above the average.
Ā» Your program first reads the numbers and computes their
average, and then compares each number with the average
to determine whether it is above the average.
Ā» The numbers must all be stored in variables in order to
accomplish this task.
https://www.facebook.com/Oxus20
Introduction
Ā» You have to declare one hundred variables and repeatedly
write almost identical code one hundred times. From the
standpoint of practicality, it is impossible to write a
program this way.
Ā» An efficient, organized approach is needed. Java and all
other high-level languages provide a data structure, the
array, which stores a fixed-size sequential collection of
elements of the same type.
https://www.facebook.com/Oxus20
Array Basics
Ā» An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables
of the same type.
Ā» Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual
variables.
https://www.facebook.com/Oxus20
Array Basics - Declaring Array Variables
Ā» To use an array in a program, you must declare a variable
to reference the array, and you must specify the type of
array the variable can reference. Here is the syntax for
declaring an array variable:
dataType[] arrayRefVar;
or
dataType arrayRefVar[]; //This style is allowed, but not preferred
The following code snippets are examples of this syntax:
double[] myList;
or
double myList[]; //This style is allowed, but not preferred
https://www.facebook.com/Oxus20
Array Basics – Creating Arrays
Ā» Unlike declarations for primitive data type variables, the
declaration of an array variable does not allocate any space in
memory for the array.
Ā» Only a storage location for the reference to an array is created.
If a variable does not reference to an array, the value of the
variable is null.
Ā» You cannot assign elements to an array unless it has already
been created.After an array variable is declared, you can create
an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
https://www.facebook.com/Oxus20
Array Basics – Creating Arrays
Ā» Declaring an array variable, creating an array, and assigning the
reference of the array to the variable can be combined in one
statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Here is an example of such a statement:
double[] myList = new double[10];
This statement declares an array variable, myList, creates an array of
ten elements of double type, and assigns its reference to myList.
https://www.facebook.com/Oxus20
Array Basics – Creating Arrays
https://www.facebook.com/Oxus20
Array Basics – Array Size and Default Values
Ā» When space for an array is allocated, the array size must
be given, to specify the number of elements that can be
stored in it.The size of an array cannot be changed after
the array is created. Size can be obtained using
arrayRefVar.length. For example, myList.length is 10.
Ā» When an array is created, its elements are assigned the
default value of 0 for the numeric primitive data types,
'u0000' for char types, and false for boolean types.
https://www.facebook.com/Oxus20
Array Basics – Array Indexed Variables
Ā» The array elements are accessed through the index.Array
indices are 0-based; that is, they start from 0 to
arrayRefVar.length-1.
Ā» Each element in the array is represented using the
following syntax, known as an indexed variable:
For example, myList[9] represents the last element
in the array myList.
https://www.facebook.com/Oxus20
Array Basics – Array Indexed Variables
Ā» After an array is created, an indexed variable can be used
in the same way as a regular variable. For example, the
following code adds the values in myList[0] and myList[1]
to myList[2]:
myList[2] = myList[0] + myList[1];
The following loop assigns 0 to myList[0], 1 to myList[1], and 9 to
myList[9]:
for (int i = 0; i < myList.length; i++)
{
myList[i] = i;
}
https://www.facebook.com/Oxus20
Array Basics – Array Initializers
Ā» Java has a shorthand notation, known as the array
initializer, which combines declaring an array, creating an
array, and initializing in one statement using the following
syntax: dataType[] arrayRefVar = {value0, value1, ..., valuek};
For example: double[] myList = {1.9, 2.9, 3.4, 3.5};
This statement declares, creates, and initializes the array myList with
four elements, which is equivalent to the statements shown below:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
https://www.facebook.com/Oxus20
Array Basics – Processing Arrays
Ā» When processing array elements, you will often use a for
loop. Here are the reasons why:
Ā» All of the elements in an array are of the same type.They
are evenly processed in the same fashion by repeatedly
using a loop.
Ā» Since the size of the array is known, it is natural to use a
for loop.
Here are some examples of processing arrays:
https://www.facebook.com/Oxus20
Array Basics – Processing Arrays
Ā» (Initializing arrays with random values)The following loop
initializes the array myList with random values between
0.0 and 99.0: double[] myList = new double[10];
Ā» (Printing arrays)To print an array, you have to print each
element in the array using a loop like the one shown
below.
https://www.facebook.com/Oxus20
Array Basics – Processing Arrays
Ā» For an array of the char[] type, it can be printed using one
print statement. For example, the following code displays
Dallas:
Ā» (Summing all elements) Use a variable named total to
store the sum. Initially total is 0.Add each element in the
array to total, using a loop like this:
double[] myList = {1,2,3,5,8};
https://www.facebook.com/Oxus20
Array Basics – Processing Arrays
Ā» (Finding the largest element) Use a variable named max
to store the largest element. Initially max is myList[0].To
find the largest element in the array myList, compare each
element in myList with max, and update max if the
element is greater than max.
https://www.facebook.com/Oxus20
Array Basics – foreach Loops
Ā» JDK 1.5 introduced a new for loop, known as foreach
loop or enhanced for loop, which enables you to traverse
the complete array sequentially without using an index
variable. For example, the following code displays all the
elements in the array myList:
double[] myList = {1.9, 2.9, 3.4, 3.5};
https://www.facebook.com/Oxus20
Copying Array
Ā» Often, in a program, you need to duplicate an array or a
part of an array. In such cases you could attempt to use the
assignment statement (=), as follows: list2 = list1;
Ā» This statement does not copy the contents of the array
referenced by list1 to list2, but merely copies the
reference value from list1 to list2.After this statement,
list1 and list2 reference to the same array.
https://www.facebook.com/Oxus20
Copying Array
Ā» In Java, you can use assignment statements to copy
primitive data type variables, but not arrays.Assigning one
array variable to another array variable actually copies one
reference to another and makes both variables point to the
same memory location.
Ā» There are three ways to copy arrays:
1. Use a loop to copy individual elements one by one.
2. Use the static arraycopy method in the System class.
3. Use the clone method to copy arrays; this will be introduced in
"Inheritance and Polymorphism."
https://www.facebook.com/Oxus20
Copying Array
Ā» You can write a loop to copy every element from the
source array to the corresponding element in the target
array.The following code, for instance, copies
sourceArray to targetArray using a for loop:
https://www.facebook.com/Oxus20
Copying Array
Ā» Another approach is to use the arraycopy method in the
java.lang.System class to copy arrays instead of using a
loop.The syntax for arraycopy is shown below:
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
Ā» The parameters srcPos and tarPos indicate the starting
positions in sourceArray and targetArray, respectively.The
number of elements copied from sourceArray to
targetArray is indicated by length. For example, you can
rewrite the loop using the following statement:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
https://www.facebook.com/Oxus20
Passing Arrays to Methods
Ā» Just as you can pass primitive type values to methods, you
can also pass arrays to methods. For example, the
following method displays the elements in an int array:
Ā» You can invoke it by passing an array. For example, the
following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:
https://www.facebook.com/Oxus20
Passing Arrays to Methods
Ā» Just as you can pass primitive type values to methods, you
can also pass arrays to methods. For example, the
following method displays the elements in an int array:
Ā» You can invoke it by passing an array. For example, the
following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:
https://www.facebook.com/Oxus20
Passing Arrays to Methods
Ā» Java uses pass-by-value to pass arguments to a method.
There are important differences between passing the
values of variables of primitive data types and passing
arrays.
Ā» For an argument of a primitive type, the argument's value
is passed.
Ā» For an argument of an array type, the value of the
argument contains a reference to an array; this reference
is passed to the method.
https://www.facebook.com/Oxus20
Passing Arrays to Methods
Ā» Take the following code, for example:
Ā» You will see that after m is invoked, x remains 1, but y[0] is 5555.
This is because y and numbers reference to the same array, although
y and numbers are independent variables
https://www.facebook.com/Oxus20
Returning an Array from a Method
Ā» You can pass arrays when invoking a method.A method
may also return an array. For example, the method shown
below returns an array that is the reversal of another
array:
https://www.facebook.com/Oxus20
(Optional) Variable-Length Argument List
Ā» JDK 1.5 enables you to pass a variable number of
arguments of the same type to a method.The parameter
in the method is declared as follows:
typeName... parameterName
Ā» In the method declaration, you specify the type followed
by an ellipsis (...) Only one variable-length parameter
may be specified in a method, and this parameter must be
the last parameter.Any regular parameters must precede
it.
https://www.facebook.com/Oxus20
(Optional) Variable-Length Argument List
Ā» Java treats a variable-
length parameter as an
array.You can pass an
array or a variable
number of arguments
to a variable-length
parameter.When
invoking a method
with a variable number
of arguments, Java
creates an array and
passes the arguments
to it.
https://www.facebook.com/Oxus20
The Array Class
Ā» The java.util.Arrays class contains various static methods for sorting
and searching arrays, comparing arrays, and filling array elements.
These methods are overloaded for all primitive types.
Ā» You can use the sort method to sort a whole array or a partial array.
For example, the following code sorts an array of numbers and an
array of characters:
https://www.facebook.com/Oxus20
The Array Class
Ā» You can use the binarySearch method to search for a key in an
array.The array must be pre-sorted in increasing order. If the
key is not in the array, the method returns -(insertion point +1).
For example, the following code searches the keys in an array of
integers and an array of characters:
https://www.facebook.com/Oxus20
The Array Class
Ā» You can use the equals method to check whether two arrays are
equal.Two arrays are equal if they have the same contents. In the
following code, list1 and list2 are equal, but list2 and list3 are
not:
https://www.facebook.com/Oxus20
The Array Class
Ā» You can use the fill method to fill in the whole array or part of
the array. For example, the following code fills list1 with 5 and
fills 8 into elements list2[1] and list2[3-1]:
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Ā» Thus far, you have used one-dimensional arrays to model linear
collections of elements.You can use a two-dimensional array to
represent a matrix or a table.
Declaring Variables of Two-Dimensional Arrays
and Creating Two-Dimensional Arrays
Ā» Here is the syntax for declaring a two-dimensional array:
dataType[][] arrayRefVar;
Ā» As an example, here is how you would declare a two-
dimensional array variable matrix of int values:
int[][] matrix;
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Ā» You can create a two-dimensional array of 5 by 5 int values and
assign it to matrix using this syntax:
matrix = new int[5][5];
Ā» Two subscripts are used in a two-dimensional array, one for the
row, and the other for the column.As in a one-dimensional
array, the index for each subscript is of the int type and starts
from 0.
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Ā» You can create a two-dimensional array of 5 by 5 int values and
assign it to matrix using this syntax:
matrix = new int[5][5];
Ā» Two subscripts are used in a two-dimensional array, one for the
row, and the other for the column.As in a one-dimensional
array, the index for each subscript is of the int type and starts
from 0.
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Ā» You can also use an array initializer to declare, create, and
initialize a two-dimensional array. For example, the following
code in (a) creates an array with the specified initial values, This
is equivalent to the code in (b).
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Obtaining the Lengths ofTwo-Dimensional Arrays
Ā» A two-dimensional array is actually an array in which each element is
a one-dimensional array.The length of an array x is the number of
elements in the array, which can be obtained using x.length. x[0],
x[1], ..., and x[x.length-1] are arrays.Their lengths can be obtained
using x[0].length, x[1].length, ..., and x[x.length-1].length.
Ā» For example, suppose x = new int[3][4], x[0], x[1], and x[2] are one-
dimensional arrays and each contains four elements, x.length is 3,
and x[0].length, x[1].length, and x[2].length are 4.
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Obtaining the Lengths ofTwo-Dimensional Arrays
Ā» A two-dimensional array is a one-dimensional array in which
each element is another one-dimensional array.
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Ragged Arrays
Ā» Each row in a two-dimensional array is itself an array.Thus the
rows can have different lengths.An array of this kind is known as
a ragged array. Here is an example of creating a ragged array:
Ā» As can be seen, triangleArray[0].length is 5, triangleArray[1].length is
4, triangleArray[2].length is 3, triangleArray[3].length is 2, and
triangleArray[4].length is 1.
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Processing Two-Dimensional Arrays
Ā» (Initializing arrays with random values)The following loop
initializes the array with random values between 0 and 99:
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Processing Two-Dimensional Arrays
Ā» (Printing arrays)To print a two-dimensional array, you have to
print each element in the array using a loop like the following:
https://www.facebook.com/Oxus20
Two-Dimensional Arrays
Processing Two-Dimensional Arrays
Ā» (Summing all elements) Use a variable named total to store the
sum. Initially total is 0.Add each element in the array to total
using a loop like this:
https://www.facebook.com/Oxus20
(Optional)Multidimensional Arrays
Ā» In the preceding section, you used a two-dimensional array to
represent a matrix or a table. Occasionally, you will need to
represent n-dimensional data structures. In Java, you can create
n-dimensional arrays for any integer n.
Ā» The way to declare two-dimensional array variables and create
two-dimensional arrays can be generalized to declare n-
dimensional array variables and create n-dimensional arrays for n
> = 3.
Ā» For example, the following syntax declares a three-dimensional
array variable.
double[][][] num= new double[5][5][5];
https://www.facebook.com/Oxus20
(Optional)Multidimensional Arrays
https://www.facebook.com/Oxus20
END
https://www.facebook.com/Oxus20
46

More Related Content

What's hot (20)

PPTX
Polymorphism in java
Elizabeth alexander
Ā 
PPTX
Constructor in java
Pavith Gunasekara
Ā 
PDF
Java threads
Prabhakaran V M
Ā 
PPTX
Multithreading in java
Monika Mishra
Ā 
PPTX
Java string handling
Salman Khan
Ā 
PPT
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
Ā 
PPTX
Java(Polymorphism)
harsh kothari
Ā 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
Ā 
PPTX
Access modifiers in java
Madishetty Prathibha
Ā 
PDF
Java variable types
Soba Arjun
Ā 
PPT
Java access modifiers
Srinivas Reddy
Ā 
PPT
Looping statements in Java
Jin Castor
Ā 
PPTX
Type casting in java
Farooq Baloch
Ā 
PDF
Java conditional statements
Kuppusamy P
Ā 
PDF
5 collection framework
Minal Maniar
Ā 
PPT
Exception Handling in JAVA
SURIT DATTA
Ā 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
Ā 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
Ā 
PPTX
Java Methods
OXUS 20
Ā 
Polymorphism in java
Elizabeth alexander
Ā 
Constructor in java
Pavith Gunasekara
Ā 
Java threads
Prabhakaran V M
Ā 
Multithreading in java
Monika Mishra
Ā 
Java string handling
Salman Khan
Ā 
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
Ā 
Java(Polymorphism)
harsh kothari
Ā 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
Ā 
Access modifiers in java
Madishetty Prathibha
Ā 
Java variable types
Soba Arjun
Ā 
Java access modifiers
Srinivas Reddy
Ā 
Looping statements in Java
Jin Castor
Ā 
Type casting in java
Farooq Baloch
Ā 
Java conditional statements
Kuppusamy P
Ā 
5 collection framework
Minal Maniar
Ā 
Exception Handling in JAVA
SURIT DATTA
Ā 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
Ā 
Static Data Members and Member Functions
MOHIT AGARWAL
Ā 
Java Methods
OXUS 20
Ā 

Similar to Java Arrays (20)

PPTX
12. arrays
M H Buddhika Ariyaratne
Ā 
PPT
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
Ā 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
Ā 
PPTX
Computer programming 2 Lesson 13
MLG College of Learning, Inc
Ā 
PPTX
Arrays in programming
TaseerRao
Ā 
PDF
Java arrays (1)
Liza Abello
Ā 
PPTX
07+08slide.pptx
MURADSANJOUM
Ā 
PPTX
Arrays in java.pptx
Nagaraju Pamarthi
Ā 
PPT
Array
PRN USM
Ā 
PDF
Array
Scott Donald
Ā 
PDF
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
Ā 
PDF
Object Oriented Programming - 5.1. Array
AndiNurkholis1
Ā 
PPT
JavaYDL6
Terry Yoast
Ā 
PPT
ch06.ppt
AqeelAbbas94
Ā 
PPT
ch06.ppt
ansariparveen06
Ā 
PPT
array Details
shivas379526
Ā 
PPT
ch06.ppt
chandrasekar529044
Ā 
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
Ā 
DOCX
Java R20 - UNIT-3.docx
Pamarthi Kumar
Ā 
PPTX
Lec 1.5 Object Oriented Programming
Badar Waseer
Ā 
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
Ā 
17-Arrays en java presentación documento
DiegoGamboaSafla
Ā 
Computer programming 2 Lesson 13
MLG College of Learning, Inc
Ā 
Arrays in programming
TaseerRao
Ā 
Java arrays (1)
Liza Abello
Ā 
07+08slide.pptx
MURADSANJOUM
Ā 
Arrays in java.pptx
Nagaraju Pamarthi
Ā 
Array
PRN USM
Ā 
Array
Scott Donald
Ā 
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
Ā 
Object Oriented Programming - 5.1. Array
AndiNurkholis1
Ā 
JavaYDL6
Terry Yoast
Ā 
ch06.ppt
AqeelAbbas94
Ā 
ch06.ppt
ansariparveen06
Ā 
array Details
shivas379526
Ā 
ch06.ppt
chandrasekar529044
Ā 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
Ā 
Java R20 - UNIT-3.docx
Pamarthi Kumar
Ā 
Lec 1.5 Object Oriented Programming
Badar Waseer
Ā 
Ad

More from OXUS 20 (20)

PPTX
Conditional Statement
OXUS 20
Ā 
PPTX
Structure programming – Java Programming – Theory
OXUS 20
Ā 
PDF
PHP Basic and Fundamental Questions and Answers with Detail Explanation
OXUS 20
Ā 
PDF
Java Applet and Graphics
OXUS 20
Ā 
PDF
Fundamentals of Database Systems Questions and Answers
OXUS 20
Ā 
PDF
Everything about Database JOINS and Relationships
OXUS 20
Ā 
PDF
Create Splash Screen with Java Step by Step
OXUS 20
Ā 
PDF
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
OXUS 20
Ā 
PDF
Web Design and Development Life Cycle and Technologies
OXUS 20
Ā 
PDF
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
OXUS 20
Ā 
PDF
Java Unicode with Cool GUI Examples
OXUS 20
Ā 
PDF
JAVA GUI PART III
OXUS 20
Ā 
PDF
Java Regular Expression PART II
OXUS 20
Ā 
PDF
Java Regular Expression PART I
OXUS 20
Ā 
PDF
Java GUI PART II
OXUS 20
Ā 
PDF
JAVA GUI PART I
OXUS 20
Ā 
PDF
Java Guessing Game Number Tutorial
OXUS 20
Ā 
PDF
JAVA Programming Questions and Answers PART III
OXUS 20
Ā 
PDF
Object Oriented Programming with Real World Examples
OXUS 20
Ā 
PDF
Object Oriented Concept Static vs. Non Static
OXUS 20
Ā 
Conditional Statement
OXUS 20
Ā 
Structure programming – Java Programming – Theory
OXUS 20
Ā 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
OXUS 20
Ā 
Java Applet and Graphics
OXUS 20
Ā 
Fundamentals of Database Systems Questions and Answers
OXUS 20
Ā 
Everything about Database JOINS and Relationships
OXUS 20
Ā 
Create Splash Screen with Java Step by Step
OXUS 20
Ā 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
OXUS 20
Ā 
Web Design and Development Life Cycle and Technologies
OXUS 20
Ā 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
OXUS 20
Ā 
Java Unicode with Cool GUI Examples
OXUS 20
Ā 
JAVA GUI PART III
OXUS 20
Ā 
Java Regular Expression PART II
OXUS 20
Ā 
Java Regular Expression PART I
OXUS 20
Ā 
Java GUI PART II
OXUS 20
Ā 
JAVA GUI PART I
OXUS 20
Ā 
Java Guessing Game Number Tutorial
OXUS 20
Ā 
JAVA Programming Questions and Answers PART III
OXUS 20
Ā 
Object Oriented Programming with Real World Examples
OXUS 20
Ā 
Object Oriented Concept Static vs. Non Static
OXUS 20
Ā 
Ad

Recently uploaded (20)

PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
Ā 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
Ā 
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
Ā 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
Ā 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
Ā 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
Ā 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
Ā 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
Ā 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
Ā 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
Ā 
PDF
Executive Business Intelligence Dashboards
vandeslie24
Ā 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
Ā 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
Ā 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
Ā 
PPTX
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
Ā 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
Ā 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
Ā 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
Ā 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
Ā 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
Ā 
Capcut Pro Crack For PC Latest Version {Fully Unlocked} 2025
hashhshs786
Ā 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
Ā 
Human Resources Information System (HRIS)
Amity University, Patna
Ā 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
Ā 
Engineering the Java Web Application (MVC)
abhishekoza1981
Ā 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
Ā 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
Ā 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
Ā 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
Ā 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
Ā 
Executive Business Intelligence Dashboards
vandeslie24
Ā 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
Ā 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
Ā 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
Ā 
An Introduction to ZAP by Checkmarx - Official Version
Simon Bennetts
Ā 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
Ā 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
Ā 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
Ā 

Java Arrays

  • 2. Outline https://www.facebook.com/Oxus20 Introduction Array Basics Copying Arrays Passing Arrays to Methods Returning an Array from a Method (Optional) Variable-Length Argument Lists The Arrays Class Two-Dimensional Arrays (Optional) Multidimensional Arrays
  • 3. Introduction Ā» Often you will have to store a large number of values during the execution of a program. Ā» Suppose, for instance, that you want to read one hundred numbers, compute their average, and find out how many numbers are above the average. Ā» Your program first reads the numbers and computes their average, and then compares each number with the average to determine whether it is above the average. Ā» The numbers must all be stored in variables in order to accomplish this task. https://www.facebook.com/Oxus20
  • 4. Introduction Ā» You have to declare one hundred variables and repeatedly write almost identical code one hundred times. From the standpoint of practicality, it is impossible to write a program this way. Ā» An efficient, organized approach is needed. Java and all other high-level languages provide a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. https://www.facebook.com/Oxus20
  • 5. Array Basics Ā» An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Ā» Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. https://www.facebook.com/Oxus20
  • 6. Array Basics - Declaring Array Variables Ā» To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable: dataType[] arrayRefVar; or dataType arrayRefVar[]; //This style is allowed, but not preferred The following code snippets are examples of this syntax: double[] myList; or double myList[]; //This style is allowed, but not preferred https://www.facebook.com/Oxus20
  • 7. Array Basics – Creating Arrays Ā» Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. Ā» Only a storage location for the reference to an array is created. If a variable does not reference to an array, the value of the variable is null. Ā» You cannot assign elements to an array unless it has already been created.After an array variable is declared, you can create an array by using the new operator with the following syntax: arrayRefVar = new dataType[arraySize]; https://www.facebook.com/Oxus20
  • 8. Array Basics – Creating Arrays Ā» Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below: dataType[] arrayRefVar = new dataType[arraySize]; Here is an example of such a statement: double[] myList = new double[10]; This statement declares an array variable, myList, creates an array of ten elements of double type, and assigns its reference to myList. https://www.facebook.com/Oxus20
  • 9. Array Basics – Creating Arrays https://www.facebook.com/Oxus20
  • 10. Array Basics – Array Size and Default Values Ā» When space for an array is allocated, the array size must be given, to specify the number of elements that can be stored in it.The size of an array cannot be changed after the array is created. Size can be obtained using arrayRefVar.length. For example, myList.length is 10. Ā» When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, 'u0000' for char types, and false for boolean types. https://www.facebook.com/Oxus20
  • 11. Array Basics – Array Indexed Variables Ā» The array elements are accessed through the index.Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1. Ā» Each element in the array is represented using the following syntax, known as an indexed variable: For example, myList[9] represents the last element in the array myList. https://www.facebook.com/Oxus20
  • 12. Array Basics – Array Indexed Variables Ā» After an array is created, an indexed variable can be used in the same way as a regular variable. For example, the following code adds the values in myList[0] and myList[1] to myList[2]: myList[2] = myList[0] + myList[1]; The following loop assigns 0 to myList[0], 1 to myList[1], and 9 to myList[9]: for (int i = 0; i < myList.length; i++) { myList[i] = i; } https://www.facebook.com/Oxus20
  • 13. Array Basics – Array Initializers Ā» Java has a shorthand notation, known as the array initializer, which combines declaring an array, creating an array, and initializing in one statement using the following syntax: dataType[] arrayRefVar = {value0, value1, ..., valuek}; For example: double[] myList = {1.9, 2.9, 3.4, 3.5}; This statement declares, creates, and initializes the array myList with four elements, which is equivalent to the statements shown below: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5; https://www.facebook.com/Oxus20
  • 14. Array Basics – Processing Arrays Ā» When processing array elements, you will often use a for loop. Here are the reasons why: Ā» All of the elements in an array are of the same type.They are evenly processed in the same fashion by repeatedly using a loop. Ā» Since the size of the array is known, it is natural to use a for loop. Here are some examples of processing arrays: https://www.facebook.com/Oxus20
  • 15. Array Basics – Processing Arrays Ā» (Initializing arrays with random values)The following loop initializes the array myList with random values between 0.0 and 99.0: double[] myList = new double[10]; Ā» (Printing arrays)To print an array, you have to print each element in the array using a loop like the one shown below. https://www.facebook.com/Oxus20
  • 16. Array Basics – Processing Arrays Ā» For an array of the char[] type, it can be printed using one print statement. For example, the following code displays Dallas: Ā» (Summing all elements) Use a variable named total to store the sum. Initially total is 0.Add each element in the array to total, using a loop like this: double[] myList = {1,2,3,5,8}; https://www.facebook.com/Oxus20
  • 17. Array Basics – Processing Arrays Ā» (Finding the largest element) Use a variable named max to store the largest element. Initially max is myList[0].To find the largest element in the array myList, compare each element in myList with max, and update max if the element is greater than max. https://www.facebook.com/Oxus20
  • 18. Array Basics – foreach Loops Ā» JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all the elements in the array myList: double[] myList = {1.9, 2.9, 3.4, 3.5}; https://www.facebook.com/Oxus20
  • 19. Copying Array Ā» Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = list1; Ā» This statement does not copy the contents of the array referenced by list1 to list2, but merely copies the reference value from list1 to list2.After this statement, list1 and list2 reference to the same array. https://www.facebook.com/Oxus20
  • 20. Copying Array Ā» In Java, you can use assignment statements to copy primitive data type variables, but not arrays.Assigning one array variable to another array variable actually copies one reference to another and makes both variables point to the same memory location. Ā» There are three ways to copy arrays: 1. Use a loop to copy individual elements one by one. 2. Use the static arraycopy method in the System class. 3. Use the clone method to copy arrays; this will be introduced in "Inheritance and Polymorphism." https://www.facebook.com/Oxus20
  • 21. Copying Array Ā» You can write a loop to copy every element from the source array to the corresponding element in the target array.The following code, for instance, copies sourceArray to targetArray using a for loop: https://www.facebook.com/Oxus20
  • 22. Copying Array Ā» Another approach is to use the arraycopy method in the java.lang.System class to copy arrays instead of using a loop.The syntax for arraycopy is shown below: arraycopy(sourceArray, srcPos, targetArray, tarPos, length); Ā» The parameters srcPos and tarPos indicate the starting positions in sourceArray and targetArray, respectively.The number of elements copied from sourceArray to targetArray is indicated by length. For example, you can rewrite the loop using the following statement: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); https://www.facebook.com/Oxus20
  • 23. Passing Arrays to Methods Ā» Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array: Ā» You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2: https://www.facebook.com/Oxus20
  • 24. Passing Arrays to Methods Ā» Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array: Ā» You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2: https://www.facebook.com/Oxus20
  • 25. Passing Arrays to Methods Ā» Java uses pass-by-value to pass arguments to a method. There are important differences between passing the values of variables of primitive data types and passing arrays. Ā» For an argument of a primitive type, the argument's value is passed. Ā» For an argument of an array type, the value of the argument contains a reference to an array; this reference is passed to the method. https://www.facebook.com/Oxus20
  • 26. Passing Arrays to Methods Ā» Take the following code, for example: Ā» You will see that after m is invoked, x remains 1, but y[0] is 5555. This is because y and numbers reference to the same array, although y and numbers are independent variables https://www.facebook.com/Oxus20
  • 27. Returning an Array from a Method Ā» You can pass arrays when invoking a method.A method may also return an array. For example, the method shown below returns an array that is the reversal of another array: https://www.facebook.com/Oxus20
  • 28. (Optional) Variable-Length Argument List Ā» JDK 1.5 enables you to pass a variable number of arguments of the same type to a method.The parameter in the method is declared as follows: typeName... parameterName Ā» In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter.Any regular parameters must precede it. https://www.facebook.com/Oxus20
  • 29. (Optional) Variable-Length Argument List Ā» Java treats a variable- length parameter as an array.You can pass an array or a variable number of arguments to a variable-length parameter.When invoking a method with a variable number of arguments, Java creates an array and passes the arguments to it. https://www.facebook.com/Oxus20
  • 30. The Array Class Ā» The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types. Ā» You can use the sort method to sort a whole array or a partial array. For example, the following code sorts an array of numbers and an array of characters: https://www.facebook.com/Oxus20
  • 31. The Array Class Ā» You can use the binarySearch method to search for a key in an array.The array must be pre-sorted in increasing order. If the key is not in the array, the method returns -(insertion point +1). For example, the following code searches the keys in an array of integers and an array of characters: https://www.facebook.com/Oxus20
  • 32. The Array Class Ā» You can use the equals method to check whether two arrays are equal.Two arrays are equal if they have the same contents. In the following code, list1 and list2 are equal, but list2 and list3 are not: https://www.facebook.com/Oxus20
  • 33. The Array Class Ā» You can use the fill method to fill in the whole array or part of the array. For example, the following code fills list1 with 5 and fills 8 into elements list2[1] and list2[3-1]: https://www.facebook.com/Oxus20
  • 34. Two-Dimensional Arrays Ā» Thus far, you have used one-dimensional arrays to model linear collections of elements.You can use a two-dimensional array to represent a matrix or a table. Declaring Variables of Two-Dimensional Arrays and Creating Two-Dimensional Arrays Ā» Here is the syntax for declaring a two-dimensional array: dataType[][] arrayRefVar; Ā» As an example, here is how you would declare a two- dimensional array variable matrix of int values: int[][] matrix; https://www.facebook.com/Oxus20
  • 35. Two-Dimensional Arrays Ā» You can create a two-dimensional array of 5 by 5 int values and assign it to matrix using this syntax: matrix = new int[5][5]; Ā» Two subscripts are used in a two-dimensional array, one for the row, and the other for the column.As in a one-dimensional array, the index for each subscript is of the int type and starts from 0. https://www.facebook.com/Oxus20
  • 36. Two-Dimensional Arrays Ā» You can create a two-dimensional array of 5 by 5 int values and assign it to matrix using this syntax: matrix = new int[5][5]; Ā» Two subscripts are used in a two-dimensional array, one for the row, and the other for the column.As in a one-dimensional array, the index for each subscript is of the int type and starts from 0. https://www.facebook.com/Oxus20
  • 37. Two-Dimensional Arrays Ā» You can also use an array initializer to declare, create, and initialize a two-dimensional array. For example, the following code in (a) creates an array with the specified initial values, This is equivalent to the code in (b). https://www.facebook.com/Oxus20
  • 38. Two-Dimensional Arrays Obtaining the Lengths ofTwo-Dimensional Arrays Ā» A two-dimensional array is actually an array in which each element is a one-dimensional array.The length of an array x is the number of elements in the array, which can be obtained using x.length. x[0], x[1], ..., and x[x.length-1] are arrays.Their lengths can be obtained using x[0].length, x[1].length, ..., and x[x.length-1].length. Ā» For example, suppose x = new int[3][4], x[0], x[1], and x[2] are one- dimensional arrays and each contains four elements, x.length is 3, and x[0].length, x[1].length, and x[2].length are 4. https://www.facebook.com/Oxus20
  • 39. Two-Dimensional Arrays Obtaining the Lengths ofTwo-Dimensional Arrays Ā» A two-dimensional array is a one-dimensional array in which each element is another one-dimensional array. https://www.facebook.com/Oxus20
  • 40. Two-Dimensional Arrays Ragged Arrays Ā» Each row in a two-dimensional array is itself an array.Thus the rows can have different lengths.An array of this kind is known as a ragged array. Here is an example of creating a ragged array: Ā» As can be seen, triangleArray[0].length is 5, triangleArray[1].length is 4, triangleArray[2].length is 3, triangleArray[3].length is 2, and triangleArray[4].length is 1. https://www.facebook.com/Oxus20
  • 41. Two-Dimensional Arrays Processing Two-Dimensional Arrays Ā» (Initializing arrays with random values)The following loop initializes the array with random values between 0 and 99: https://www.facebook.com/Oxus20
  • 42. Two-Dimensional Arrays Processing Two-Dimensional Arrays Ā» (Printing arrays)To print a two-dimensional array, you have to print each element in the array using a loop like the following: https://www.facebook.com/Oxus20
  • 43. Two-Dimensional Arrays Processing Two-Dimensional Arrays Ā» (Summing all elements) Use a variable named total to store the sum. Initially total is 0.Add each element in the array to total using a loop like this: https://www.facebook.com/Oxus20
  • 44. (Optional)Multidimensional Arrays Ā» In the preceding section, you used a two-dimensional array to represent a matrix or a table. Occasionally, you will need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. Ā» The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n- dimensional array variables and create n-dimensional arrays for n > = 3. Ā» For example, the following syntax declares a three-dimensional array variable. double[][][] num= new double[5][5][5]; https://www.facebook.com/Oxus20