SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Java Collections
Java  Collections Java  Collections
Java Collections
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Java arrays
Java arraysJava arrays
Java arrays
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Array in Java
Array in JavaArray in Java
Array in Java
 
array of object pointer in c++
array of object pointer in c++array of object pointer in c++
array of object pointer in c++
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java Methods
Java MethodsJava Methods
Java Methods
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 

Ähnlich wie Java Arrays

Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docxPamarthi Kumar
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm KristinaBorooah
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfajajkhan16
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collectionsphanleson
 

Ähnlich wie Java Arrays (20)

Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Ppt chapter09
Ppt chapter09Ppt chapter09
Ppt chapter09
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Arrays
ArraysArrays
Arrays
 
Array andfunction
Array andfunctionArray andfunction
Array andfunction
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm Arrays in Data Structure and Algorithm
Arrays in Data Structure and Algorithm
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
12. arrays
12. arrays12. arrays
12. arrays
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Arrays
ArraysArrays
Arrays
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Generics Collections
Generics CollectionsGenerics Collections
Generics Collections
 

Mehr von OXUS 20

Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement OXUS 20
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryOXUS 20
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersOXUS 20
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsOXUS 20
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepOXUS 20
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaOXUS 20
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART IOXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIOXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 

Mehr von OXUS 20 (20)

Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 

Kürzlich hochgeladen

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedDelhi Call girls
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxalwaysnagaraju26
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 

Kürzlich hochgeladen (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

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