SlideShare a Scribd company logo
1 of 4
Download to read offline
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
 
Array data structure
Array data structureArray data structure
Array data structure
 
Array Presentation
Array PresentationArray Presentation
Array Presentation
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Arrays
ArraysArrays
Arrays
 
Arrays Basics
Arrays BasicsArrays Basics
Arrays Basics
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Arrays
ArraysArrays
Arrays
 
Array in c#
Array in c#Array in c#
Array in c#
 
Array in Java
Array in JavaArray in Java
Array in Java
 
Array lecture
Array lectureArray lecture
Array lecture
 
12. arrays
12. arrays12. arrays
12. arrays
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
intorduction to Arrays in java
intorduction to Arrays in javaintorduction to Arrays in java
intorduction to Arrays in java
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
LectureNotes-03-DSA
LectureNotes-03-DSALectureNotes-03-DSA
LectureNotes-03-DSA
 
Arrays
ArraysArrays
Arrays
 

Similar to Java arrays (1)

Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docxPamarthi Kumar
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programmingTaseerRao
 
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
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfaroraopticals15
 
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
 
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
 
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
 

Similar to Java arrays (1) (20)

Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
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 properties
Array propertiesArray properties
Array properties
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Arrays
ArraysArrays
Arrays
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
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
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
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
 
Chap09
Chap09Chap09
Chap09
 
Arrays
ArraysArrays
Arrays
 
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
 
OOPs with java
OOPs with javaOOPs with java
OOPs with java
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 
Arrays
ArraysArrays
Arrays
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
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
 

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.)