際際滷

際際滷Share a Scribd company logo
http://www.tutorialspoint.com/java/java_arrays.htm Copyright 息 tutorialspoint.com
JAVA - ARRAYS
Java provides a data structure, the array, whichstores a fixed-size sequentialcollectionof elements of the
same type. Anarray is used to store a collectionof data, but it is oftenmore usefulto think of anarray as a
collectionof variables of the same type.
Instead of declaring individualvariables, suchas number0, number1, ..., and number99, youdeclare one array
variable suchas numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
This tutorialintroduces how to declare array variables, create arrays, and process arrays using indexed
variables.
Declaring Array Variables:
To use anarray ina program, youmust declare a variable to reference the array, and youmust specify the type
of array the variable canreference. Here is the syntax for declaring anarray variable:
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from
the C/C++ language and was adopted inJava to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays:
Youcancreate anarray by using the new operator withthe following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:
It creates anarray using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring anarray variable, creating anarray, and assigning the reference of the array to the variable canbe
combined inone statement, as shownbelow:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively youcancreate arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed throughthe index. Array indices are 0-based; that is, they start from0 to
arrayRefVar.length-1.
Example:
Following statement declares anarray variable, myList, creates anarray of 10 elements of double type, and
assigns its reference to myList.:
double[] myList = new double[10];
Following picture represents array myList. Here myList holds tendouble values and the indices are from0 to 9.
Processing Arrays:
Whenprocessing array elements, we oftenuse either for loop or foreachloop because allof the elements inan
array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop, knownas foreachloop or enhanced for loop, whichenables youto traverse
the complete array sequentially without using anindex variable.
Example:
The following code displays allthe elements inthe array myList:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Passing Arrays to Methods:
Just as youcanpass primitive type values to methods, youcanalso pass arrays to methods. For example, the
following method displays the elements inanint array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Youcaninvoke it by passing anarray. For example, the following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
A method may also returnanarray. For example, the method shownbelow returns anarray that is the reversalof
another array:
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
The Arrays 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 allprimitive types.
SN Methods with Description
1 public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary
searchalgorithm. The array must be sorted prior to making this call. This returns index of the search
key, if it is contained inthe list; otherwise, (-(insertionpoint + 1).
2 public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equalto one another. Two arrays are considered
equalif botharrays containthe same number of elements, and allcorresponding pairs of elements in
the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by
allother premitive data types ( Byte, short, Int etc.)
3 public static void fill(int[] a, int val)
Assigns the specified int value to eachelement of the specified array of ints. Same method could be
used by allother premitive data types ( Byte, short, Int etc.)
4 public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the naturalordering of its
elements. Same method could be used by allother premitive data types ( Byte, short, Int etc.)

More Related Content

What's hot (20)

Java Arrays
Java ArraysJava Arrays
Java Arrays
OXUS 20
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
Array Presentation
Array PresentationArray Presentation
Array Presentation
Deep Prajapati Microplacer
Array in Java
Array in JavaArray in Java
Array in Java
Ali shah
Arrays
ArraysArrays
Arrays
SARITHA REDDY
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
Nikhil Pandit
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
Arrays
ArraysArrays
Arrays
Dr. Abhineet Anand
Array in c#
Array in c#Array in c#
Array in c#
Prem Kumar Badri
Array in Java
Array in JavaArray in Java
Array in Java
Shehrevar Davierwala
Array lecture
Array lectureArray lecture
Array lecture
Joan Sa単o
12. arrays
12. arrays12. arrays
12. arrays
M H Buddhika Ariyaratne
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
Gopal Ji Singh
intorduction to Arrays in java
intorduction to Arrays in javaintorduction to Arrays in java
intorduction to Arrays in java
Muthukumaran Subramanian
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
Haitham El-Ghareeb
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
Victor Palmar
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
Haitham El-Ghareeb
Arrays
ArraysArrays
Arrays
Faisal Aziz

Similar to Java arrays (1) (20)

07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
MURADSANJOUM
17-Arrays en java presentaci坦n documento
17-Arrays en java presentaci坦n documento17-Arrays en java presentaci坦n documento
17-Arrays en java presentaci坦n documento
DiegoGamboaSafla
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
Arrays in java.pptx
Arrays in java.pptxArrays in java.pptx
Arrays in java.pptx
Nagaraju Pamarthi
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
Abbott
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
Lec 1.5 Object Oriented Programming
Lec 1.5 Object Oriented ProgrammingLec 1.5 Object Oriented Programming
Lec 1.5 Object Oriented Programming
Badar Waseer
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
AqeelAbbas94
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
array Details
array Detailsarray Details
array Details
shivas379526
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
chandrasekar529044
Data structure lecture 2 (pdf)
Data structure lecture 2 (pdf)Data structure lecture 2 (pdf)
Data structure lecture 2 (pdf)
Abbott
Object Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. ArrayObject Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. Array
AndiNurkholis1
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
Introduction-to-Arrays-in-Java . Exploring array
Introduction-to-Arrays-in-Java . Exploring arrayIntroduction-to-Arrays-in-Java . Exploring array
Introduction-to-Arrays-in-Java . Exploring array
AbdulSamad264371
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock
JavaYDL6
JavaYDL6JavaYDL6
JavaYDL6
Terry Yoast
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
MURADSANJOUM
17-Arrays en java presentaci坦n documento
17-Arrays en java presentaci坦n documento17-Arrays en java presentaci坦n documento
17-Arrays en java presentaci坦n documento
DiegoGamboaSafla
Arrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.pptArrays Basicfundamentaldatastructure.ppt
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
Data structure lecture 2
Data structure lecture 2Data structure lecture 2
Data structure lecture 2
Abbott
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
Chap1 array
Chap1 arrayChap1 array
Chap1 array
raksharao
Lec 1.5 Object Oriented Programming
Lec 1.5 Object Oriented ProgrammingLec 1.5 Object Oriented Programming
Lec 1.5 Object Oriented Programming
Badar Waseer
Data structure lecture 2 (pdf)
Data structure lecture 2 (pdf)Data structure lecture 2 (pdf)
Data structure lecture 2 (pdf)
Abbott
Object Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. ArrayObject Oriented Programming - 5.1. Array
Object Oriented Programming - 5.1. Array
AndiNurkholis1
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docxArraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
Introduction-to-Arrays-in-Java . Exploring array
Introduction-to-Arrays-in-Java . Exploring arrayIntroduction-to-Arrays-in-Java . Exploring array
Introduction-to-Arrays-in-Java . Exploring array
AbdulSamad264371
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
Gina Bullock

Java arrays (1)

  • 1. http://www.tutorialspoint.com/java/java_arrays.htm Copyright 息 tutorialspoint.com JAVA - ARRAYS Java provides a data structure, the array, whichstores a fixed-size sequentialcollectionof elements of the same type. Anarray is used to store a collectionof data, but it is oftenmore usefulto think of anarray as a collectionof variables of the same type. Instead of declaring individualvariables, suchas number0, number1, ..., and number99, youdeclare one array variable suchas numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorialintroduces how to declare array variables, create arrays, and process arrays using indexed variables. Declaring Array Variables: To use anarray ina program, youmust declare a variable to reference the array, and youmust specify the type of array the variable canreference. Here is the syntax for declaring anarray variable: dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way. Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted inJava to accommodate C/C++ programmers. Example: The following code snippets are examples of this syntax: double[] myList; // preferred way. or double myList[]; // works but not preferred way. Creating Arrays: Youcancreate anarray by using the new operator withthe following syntax: arrayRefVar = new dataType[arraySize]; The above statement does two things: It creates anarray using new dataType[arraySize]; It assigns the reference of the newly created array to the variable arrayRefVar. Declaring anarray variable, creating anarray, and assigning the reference of the array to the variable canbe combined inone statement, as shownbelow: dataType[] arrayRefVar = new dataType[arraySize]; Alternatively youcancreate arrays as follows: dataType[] arrayRefVar = {value0, value1, ..., valuek}; The array elements are accessed throughthe index. Array indices are 0-based; that is, they start from0 to arrayRefVar.length-1.
  • 2. Example: Following statement declares anarray variable, myList, creates anarray of 10 elements of double type, and assigns its reference to myList.: double[] myList = new double[10]; Following picture represents array myList. Here myList holds tendouble values and the indices are from0 to 9. Processing Arrays: Whenprocessing array elements, we oftenuse either for loop or foreachloop because allof the elements inan array are of the same type and the size of the array is known. Example: Here is a complete example of showing how to create, initialize and process arrays: public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } } This would produce following result: 1.9 2.9 3.4 3.5
  • 3. Total is 11.7 Max is 3.5 The foreach Loops: JDK 1.5 introduced a new for loop, knownas foreachloop or enhanced for loop, whichenables youto traverse the complete array sequentially without using anindex variable. Example: The following code displays allthe elements inthe array myList: public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } } This would produce following result: 1.9 2.9 3.4 3.5 Passing Arrays to Methods: Just as youcanpass primitive type values to methods, youcanalso pass arrays to methods. For example, the following method displays the elements inanint array: public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } Youcaninvoke it by passing anarray. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2: printArray(new int[]{3, 1, 2, 6, 4, 2}); Returning an Array from a Method: A method may also returnanarray. For example, the method shownbelow returns anarray that is the reversalof another array: public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; } The Arrays 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 allprimitive types.
  • 4. SN Methods with Description 1 public static int binarySearch(Object[] a, Object key) Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary searchalgorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained inthe list; otherwise, (-(insertionpoint + 1). 2 public static boolean equals(long[] a, long[] a2) Returns true if the two specified arrays of longs are equalto one another. Two arrays are considered equalif botharrays containthe same number of elements, and allcorresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by allother premitive data types ( Byte, short, Int etc.) 3 public static void fill(int[] a, int val) Assigns the specified int value to eachelement of the specified array of ints. Same method could be used by allother premitive data types ( Byte, short, Int etc.) 4 public static void sort(Object[] a) Sorts the specified array of objects into ascending order, according to the naturalordering of its elements. Same method could be used by allother premitive data types ( Byte, short, Int etc.)