SlideShare 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

PPTX
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
PPTX
Java arrays
Jin Castor
 
PDF
An Introduction to Programming in Java: Arrays
Martin Chapman
 
PPTX
Array
Anil Neupane
 
PPT
Array
PRN USM
 
PPTX
Presentation on array
topu93
 
PPTX
Arrays in java
Arzath Areeff
 
PPTX
ARRAY
ayush raj
 
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
Java arrays
Jin Castor
 
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Array
PRN USM
 
Presentation on array
topu93
 
Arrays in java
Arzath Areeff
 
ARRAY
ayush raj
 

What's hot (20)

PDF
Java Arrays
OXUS 20
 
PDF
Array data structure
maamir farooq
 
PPT
Array Presentation
Deep Prajapati Microplacer
 
PPTX
Array in Java
Ali shah
 
PPT
Arrays
SARITHA REDDY
 
PPT
Arrays Basics
Nikhil Pandit
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Array in c#
Prem Kumar Badri
 
PPT
Array in Java
Shehrevar Davierwala
 
PPTX
Array lecture
Joan Saño
 
PPTX
12. arrays
M H Buddhika Ariyaratne
 
PPTX
Array in C# 3.5
Gopal Ji Singh
 
PDF
intorduction to Arrays in java
Muthukumaran Subramanian
 
PDF
LectureNotes-05-DSA
Haitham El-Ghareeb
 
PPT
Lecture 2a arrays
Victor Palmar
 
PPT
9781439035665 ppt ch09
Terry Yoast
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
PDF
LectureNotes-03-DSA
Haitham El-Ghareeb
 
PPT
Arrays
Faisal Aziz
 
Java Arrays
OXUS 20
 
Array data structure
maamir farooq
 
Array Presentation
Deep Prajapati Microplacer
 
Array in Java
Ali shah
 
Arrays Basics
Nikhil Pandit
 
Arrays in Java
Naz Abdalla
 
Array in c#
Prem Kumar Badri
 
Array in Java
Shehrevar Davierwala
 
Array lecture
Joan Saño
 
Array in C# 3.5
Gopal Ji Singh
 
intorduction to Arrays in java
Muthukumaran Subramanian
 
LectureNotes-05-DSA
Haitham El-Ghareeb
 
Lecture 2a arrays
Victor Palmar
 
9781439035665 ppt ch09
Terry Yoast
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
LectureNotes-03-DSA
Haitham El-Ghareeb
 
Arrays
Faisal Aziz
 
Ad

Similar to Java arrays (1) (20)

PPTX
07+08slide.pptx
MURADSANJOUM
 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
 
PPT
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
PPTX
ch 7 single dimension array in oop .pptx
nilampatoliya
 
PPTX
Arrays in java.pptx
Nagaraju Pamarthi
 
DOC
Data structure lecture 2
Abbott
 
DOCX
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
PPTX
Arrays in programming
TaseerRao
 
PPTX
Chap1 array
raksharao
 
PPTX
Lec 1.5 Object Oriented Programming
Badar Waseer
 
PDF
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
PPT
ch06.ppt
ansariparveen06
 
PPT
ch06.ppt
chandrasekar529044
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
array Details
shivas379526
 
PDF
Data structure lecture 2 (pdf)
Abbott
 
PDF
Object Oriented Programming - 5.1. Array
AndiNurkholis1
 
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
PPTX
Introduction-to-Arrays-in-Java . Exploring array
AbdulSamad264371
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
07+08slide.pptx
MURADSANJOUM
 
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Arrays Basicfundamentaldatastructure.ppt
JyothiAmpally
 
ch 7 single dimension array in oop .pptx
nilampatoliya
 
Arrays in java.pptx
Nagaraju Pamarthi
 
Data structure lecture 2
Abbott
 
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Arrays in programming
TaseerRao
 
Chap1 array
raksharao
 
Lec 1.5 Object Oriented Programming
Badar Waseer
 
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
ch06.ppt
ansariparveen06
 
ch06.ppt
AqeelAbbas94
 
array Details
shivas379526
 
Data structure lecture 2 (pdf)
Abbott
 
Object Oriented Programming - 5.1. Array
AndiNurkholis1
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
Introduction-to-Arrays-in-Java . Exploring array
AbdulSamad264371
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Ad

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