SlideShare a Scribd company logo
Introduction to Arrays
What are 1-D arrays?    An  array  is an  object  that is used to store a list of values of the  same type .  It is made out of a contiguous block of memory that is divided into a number of "slots“ or variables.   Each slot can be accessed by using its  index (or subscript) . If there are N slots in an array, the indexes will be 0 through N-1. The diagram on the right shows a 5-element array. The indexes are from  0  to  4 An array that uses a single subscript is called a  one dimensional  array.    Two dimensional arrays, three dimensional arrays, and higher dimensional arrays also exist:
1-D Array Declaration   For any type T,  T[ ] is a class , whose instances are arrays of  type T. Thus, the following statement declares a reference variable,  b,  of type T array : T[]  b; For any positive integer n, the following expression   creates a new T[ ] object of size n and stores its reference in  b : b = new  T[n] ; As usual, the two expressions can be combined together as: T[] b = new T[n] ;   For example, the following declares an  int[]  ,  grades,  of size 10:   int[ ] grades = new int[10];
1-D Array Declaration (cont’d) The declaration of an array of size n creates n variables of the base type T. These variables are indexed starting from 0 to n-1. They are called  subscripted variables .  A subscripted variable can be used anywhere an ordinary variable of the same type can be used. The slots of an array are initialized to the default value for their type.  Each slot of a numeric array is initialized to zero.  Each array object has a public instance variable, length, that stores the size of the array. Thus, the following statement prints 10, the size of grades: System.out.println(grades.length); Once an array has been constructed, its length does not change. Other examples of 1D-array declaration are: double[ ] price = new double[500];  // each element is initialized to 0.0 boolean[ ] flag = new boolean[20];  // each element is initialized to false
Accessing elements of a 1-D Array   A particular variable is accessed by indexing the array reference with the index (subscript) of the variable in square brackets :   grades[4]  =  20;   The following example, re-initializes each variable with twice its index:  int[] grades = new int[10];   for(int i = 0; i < grades.length; i++) grades[i] =  2*i ;   The use of  grades.length  instead of 10   makes the code more general.
Accessing elements of a 1-D Array (cont'd  ) The following prints the values of the array re-initialized by the example in the previous slide.     for(int i = 0; i < grades . length; i++) System.out.print(grades[i] + “  “); Output: 0  2  4  6  8  10  14  16  18 Note: Trying to access an element with an invalid index causes a run-time error: ArrayIndexOutOfBoundsException: int x = grades[10];  // causes run-time error
Accessing elements of a 1-D Array (cont'd  ) The indexes (subscripts) of an array must always be of integer type except  long   ( int, char, short, byte ). An array index can be any expression that evaluates to an integer within the allowed index range: double[] val = new double[20]; int k  = 3; val[0] =  1.5; val[1] = 10.0; val[2] = 15.5; val[k] = val[k-1] + val[k - 2];  // same as val[3] = val[2] + val[1] val[ k*2 + 3 ] = 24 + val[13];  // same as: val[ 9 ] = 24 + 0.0 System.out.println( &quot;val[&quot; + k + &quot;] == &quot; + val[k] );  // output: val[3] = 25.5 Note: the following are invalid because the index is not of type int, char, short, or byte: long k = 5L; val[k] = 33.2; val[8.0] = 75.5; 
Using Subscripts with an Array Enhanced  for  loop Cycle through array  Without specifying starting and ending points for loop control variable for(int val : scoreArray) System.out.println(val);
Initializer List  Initializer list can be used to instantiate and initialize an array in one step:   int[ ]  prime  =  {2 ,  3,  5,  7,  11,  13,  17,  19,  23,  29} ;   char[ ]  letterGrade  =  { ’ A ’ ,  ‘ B ’ ,  ‘C’,  ‘ D ’ ,  ‘ F ’ };   It is actually the compiler that fills the gap. Thus, in the first example, the compiler would  add the following:  int[]  prime  =  new  int[10]; prime[0]  =  2;  prime[1]  =  3;  ...  prime[9]  =  29;   Observe that when an initializer list is used:  The new operator is not required.  The size is not required; it is computed by the compiler.
Copying one array to another  Consider the following declarations:   int[ ] array1  =  {22,  3,  50,  7,  11,  13,  17};   int[ ] array2  = {3,  5,  8,  20,  0,  100,  40};   The assignment statement : array1 = array2;  does not copy the contents of  array2  to  array1 ; it makes the reference  array1  to refer to the array object referenced by  array2 . The object that was referenced by  array1  becomes garbage.  To copy the contents of  array2  to  array1 , code like the following is used:   for(int k = 0; k < array2.length; k++) array1[k] = array2[k];
Array used as a Parameter Remember that a parameter is data that is supplied to a method just before it starts running. The following method prints the content of an  int  array passed to it as parameter: class MyArray { public void print (int[] x) {   for(int i = 0; i < x.length; i++)   System.out.print(x[i]+ &quot;  &quot;);   System.out.println();   } }  The method is written using the parameter  x  to refer to the actual data that it will be supplied with.  The method is written without referring to any particular data.  When the  print()  method is running it has a reference to an array object in its parameter  x .
Example(1) class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 =  { -20, 19, 1, 5, -1, 27 } ; System.out.print  (&quot;The array is: &quot; ); operate.print( ar1 ); } } public static void print (int[] x) { for(int i = 0; i < x.length; i++) System.out.print(a[x]+ &quot;  &quot;); System.out.println(); } MyArray print(x) operate -20 19 1 5 -1 27 ar1
Parameter Connected to New Data Could the main() method create a second array and use the print() method with it? Example (2): What is the output? class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 = { -20, 19, 1, 5, -1, 27 } ;   int[] ar2 = {1, 2, 6, 3, 9, 5}; System.out.print(&quot;The array is: &quot; ); operate.print( ar1 );   System.out.print(&quot;The second array is: &quot; );   operate.print( ar2 ); } } The array is: -20 19 1 5 -1 27 The second array is: 1 2 6 3 9 5
Using Two-Dimensional and Multidimensional Arrays One-dimensional or single-dimensional array Picture as column of values Elements accessed using single subscript Two-dimensional arrays  Two or more columns of values Rows and columns Use two subscripts Matrix or table int[][] someNumbers = new int[3][4];
View of a Two-Dimensional Array in Memory
Using Two-Dimensional and Multidimensional Arrays (continued) int[][] rents = { {400, 450, 510},  {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600} }; public static void displayScores(int[][]scoresArray)
Using Two-Dimensional and Multidimensional Arrays (continued) Multidimensional arrays More than two dimensions Create arrays of any size Keep track of order of variables needed as subscripts Don’t exhaust computer’s memory

More Related Content

What's hot (20)

PPTX
2- Dimensional Arrays
Education Front
 
PPTX
SUBQUERIES.pptx
RenugadeviR5
 
PPT
Array
PRN USM
 
PPTX
Two dimensional arrays
Neeru Mittal
 
PPTX
Pointers in c++
Vineeta Garg
 
PPT
C++ Arrays
أحمد محمد
 
PPT
Abstract data types
Poojith Chowdhary
 
PPTX
Data structure & its types
Rameesha Sadaqat
 
PDF
sparse matrix in data structure
MAHALAKSHMI P
 
PPTX
Integrity Constraints
Megha yadav
 
PPTX
Introduction to Array ppt
sandhya yadav
 
PDF
Java Arrays
OXUS 20
 
PPT
Two Dimensional Array
dincyjain
 
PPTX
trees in data structure
shameen khan
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Polymorphism in c++(ppt)
Sanjit Shaw
 
PDF
linked lists in data structures
DurgaDeviCbit
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PPTX
constructors in java ppt
kunal kishore
 
2- Dimensional Arrays
Education Front
 
SUBQUERIES.pptx
RenugadeviR5
 
Array
PRN USM
 
Two dimensional arrays
Neeru Mittal
 
Pointers in c++
Vineeta Garg
 
C++ Arrays
أحمد محمد
 
Abstract data types
Poojith Chowdhary
 
Data structure & its types
Rameesha Sadaqat
 
sparse matrix in data structure
MAHALAKSHMI P
 
Integrity Constraints
Megha yadav
 
Introduction to Array ppt
sandhya yadav
 
Java Arrays
OXUS 20
 
Two Dimensional Array
dincyjain
 
trees in data structure
shameen khan
 
Arrays in Java
Naz Abdalla
 
Polymorphism in c++(ppt)
Sanjit Shaw
 
linked lists in data structures
DurgaDeviCbit
 
Union in C programming
Kamal Acharya
 
Access specifiers(modifiers) in java
HrithikShinde
 
constructors in java ppt
kunal kishore
 

Similar to Java: Introduction to Arrays (20)

PPT
Data Structure Midterm Lesson Arrays
Maulen Bale
 
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
PPT
9781439035665 ppt ch09
Terry Yoast
 
PPT
Chap09
Terry Yoast
 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
 
PDF
Array
Ravi_Kant_Sahu
 
PPT
Java căn bản - Chapter10
Vince Vo
 
PPT
Md05 arrays
Rakesh Madugula
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
ch06.ppt
ansariparveen06
 
PPT
array Details
shivas379526
 
PPT
ch06.ppt
chandrasekar529044
 
PPTX
Arrays in programming
TaseerRao
 
PDF
Learn Java Part 8
Gurpreet singh
 
PPT
Visula C# Programming Lecture 5
Abou Bakr Ashraf
 
PPTX
6_Array.pptx
shafat6712
 
PDF
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PDF
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
9781439035665 ppt ch09
Terry Yoast
 
Chap09
Terry Yoast
 
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Java căn bản - Chapter10
Vince Vo
 
Md05 arrays
Rakesh Madugula
 
ch06.ppt
AqeelAbbas94
 
ch06.ppt
ansariparveen06
 
array Details
shivas379526
 
Arrays in programming
TaseerRao
 
Learn Java Part 8
Gurpreet singh
 
Visula C# Programming Lecture 5
Abou Bakr Ashraf
 
6_Array.pptx
shafat6712
 
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Ad

More from Tareq Hasan (20)

PPTX
Grow Your Career with WordPress
Tareq Hasan
 
PDF
Caching in WordPress
Tareq Hasan
 
PDF
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
PDF
Composer - The missing package manager for PHP
Tareq Hasan
 
PDF
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
PPT
08 c++ Operator Overloading.ppt
Tareq Hasan
 
PPT
02 c++ Array Pointer
Tareq Hasan
 
PPT
01 c++ Intro.ppt
Tareq Hasan
 
PPT
chapter22.ppt
Tareq Hasan
 
PPT
chapter - 6.ppt
Tareq Hasan
 
PPT
Algorithm.ppt
Tareq Hasan
 
PPT
chapter-8.ppt
Tareq Hasan
 
PPT
chapter23.ppt
Tareq Hasan
 
PPT
chapter24.ppt
Tareq Hasan
 
PPT
Algorithm: priority queue
Tareq Hasan
 
PPT
Algorithm: Quick-Sort
Tareq Hasan
 
PPT
Java: GUI
Tareq Hasan
 
PPT
Java: Inheritance
Tareq Hasan
 
PPT
Java: Exception
Tareq Hasan
 
PPT
Java: Class Design Examples
Tareq Hasan
 
Grow Your Career with WordPress
Tareq Hasan
 
Caching in WordPress
Tareq Hasan
 
How to Submit a plugin to WordPress.org Repository
Tareq Hasan
 
Composer - The missing package manager for PHP
Tareq Hasan
 
WordPress Theme & Plugin development best practices - phpXperts seminar 2011
Tareq Hasan
 
08 c++ Operator Overloading.ppt
Tareq Hasan
 
02 c++ Array Pointer
Tareq Hasan
 
01 c++ Intro.ppt
Tareq Hasan
 
chapter22.ppt
Tareq Hasan
 
chapter - 6.ppt
Tareq Hasan
 
Algorithm.ppt
Tareq Hasan
 
chapter-8.ppt
Tareq Hasan
 
chapter23.ppt
Tareq Hasan
 
chapter24.ppt
Tareq Hasan
 
Algorithm: priority queue
Tareq Hasan
 
Algorithm: Quick-Sort
Tareq Hasan
 
Java: GUI
Tareq Hasan
 
Java: Inheritance
Tareq Hasan
 
Java: Exception
Tareq Hasan
 
Java: Class Design Examples
Tareq Hasan
 
Ad

Recently uploaded (20)

PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Difference between write and update in odoo 18
Celine George
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 

Java: Introduction to Arrays

  • 2. What are 1-D arrays?   An array is an object that is used to store a list of values of the same type . It is made out of a contiguous block of memory that is divided into a number of &quot;slots“ or variables. Each slot can be accessed by using its index (or subscript) . If there are N slots in an array, the indexes will be 0 through N-1. The diagram on the right shows a 5-element array. The indexes are from 0 to 4 An array that uses a single subscript is called a one dimensional array.   Two dimensional arrays, three dimensional arrays, and higher dimensional arrays also exist:
  • 3. 1-D Array Declaration For any type T, T[ ] is a class , whose instances are arrays of type T. Thus, the following statement declares a reference variable, b, of type T array : T[] b; For any positive integer n, the following expression creates a new T[ ] object of size n and stores its reference in b : b = new T[n] ; As usual, the two expressions can be combined together as: T[] b = new T[n] ;   For example, the following declares an int[] , grades, of size 10:   int[ ] grades = new int[10];
  • 4. 1-D Array Declaration (cont’d) The declaration of an array of size n creates n variables of the base type T. These variables are indexed starting from 0 to n-1. They are called subscripted variables . A subscripted variable can be used anywhere an ordinary variable of the same type can be used. The slots of an array are initialized to the default value for their type. Each slot of a numeric array is initialized to zero. Each array object has a public instance variable, length, that stores the size of the array. Thus, the following statement prints 10, the size of grades: System.out.println(grades.length); Once an array has been constructed, its length does not change. Other examples of 1D-array declaration are: double[ ] price = new double[500]; // each element is initialized to 0.0 boolean[ ] flag = new boolean[20]; // each element is initialized to false
  • 5. Accessing elements of a 1-D Array A particular variable is accessed by indexing the array reference with the index (subscript) of the variable in square brackets : grades[4] = 20; The following example, re-initializes each variable with twice its index: int[] grades = new int[10]; for(int i = 0; i < grades.length; i++) grades[i] = 2*i ; The use of grades.length instead of 10 makes the code more general.
  • 6. Accessing elements of a 1-D Array (cont'd ) The following prints the values of the array re-initialized by the example in the previous slide.   for(int i = 0; i < grades . length; i++) System.out.print(grades[i] + “ “); Output: 0 2 4 6 8 10 14 16 18 Note: Trying to access an element with an invalid index causes a run-time error: ArrayIndexOutOfBoundsException: int x = grades[10]; // causes run-time error
  • 7. Accessing elements of a 1-D Array (cont'd ) The indexes (subscripts) of an array must always be of integer type except long ( int, char, short, byte ). An array index can be any expression that evaluates to an integer within the allowed index range: double[] val = new double[20]; int k = 3; val[0] = 1.5; val[1] = 10.0; val[2] = 15.5; val[k] = val[k-1] + val[k - 2]; // same as val[3] = val[2] + val[1] val[ k*2 + 3 ] = 24 + val[13]; // same as: val[ 9 ] = 24 + 0.0 System.out.println( &quot;val[&quot; + k + &quot;] == &quot; + val[k] ); // output: val[3] = 25.5 Note: the following are invalid because the index is not of type int, char, short, or byte: long k = 5L; val[k] = 33.2; val[8.0] = 75.5; 
  • 8. Using Subscripts with an Array Enhanced for loop Cycle through array Without specifying starting and ending points for loop control variable for(int val : scoreArray) System.out.println(val);
  • 9. Initializer List Initializer list can be used to instantiate and initialize an array in one step: int[ ] prime = {2 , 3, 5, 7, 11, 13, 17, 19, 23, 29} ; char[ ] letterGrade = { ’ A ’ , ‘ B ’ , ‘C’, ‘ D ’ , ‘ F ’ }; It is actually the compiler that fills the gap. Thus, in the first example, the compiler would add the following: int[] prime = new int[10]; prime[0] = 2; prime[1] = 3; ... prime[9] = 29; Observe that when an initializer list is used: The new operator is not required. The size is not required; it is computed by the compiler.
  • 10. Copying one array to another Consider the following declarations: int[ ] array1 = {22, 3, 50, 7, 11, 13, 17}; int[ ] array2 = {3, 5, 8, 20, 0, 100, 40}; The assignment statement : array1 = array2; does not copy the contents of array2 to array1 ; it makes the reference array1 to refer to the array object referenced by array2 . The object that was referenced by array1 becomes garbage. To copy the contents of array2 to array1 , code like the following is used: for(int k = 0; k < array2.length; k++) array1[k] = array2[k];
  • 11. Array used as a Parameter Remember that a parameter is data that is supplied to a method just before it starts running. The following method prints the content of an int array passed to it as parameter: class MyArray { public void print (int[] x) { for(int i = 0; i < x.length; i++) System.out.print(x[i]+ &quot; &quot;); System.out.println(); } } The method is written using the parameter x to refer to the actual data that it will be supplied with. The method is written without referring to any particular data. When the print() method is running it has a reference to an array object in its parameter x .
  • 12. Example(1) class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 = { -20, 19, 1, 5, -1, 27 } ; System.out.print (&quot;The array is: &quot; ); operate.print( ar1 ); } } public static void print (int[] x) { for(int i = 0; i < x.length; i++) System.out.print(a[x]+ &quot; &quot;); System.out.println(); } MyArray print(x) operate -20 19 1 5 -1 27 ar1
  • 13. Parameter Connected to New Data Could the main() method create a second array and use the print() method with it? Example (2): What is the output? class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 = { -20, 19, 1, 5, -1, 27 } ; int[] ar2 = {1, 2, 6, 3, 9, 5}; System.out.print(&quot;The array is: &quot; ); operate.print( ar1 ); System.out.print(&quot;The second array is: &quot; ); operate.print( ar2 ); } } The array is: -20 19 1 5 -1 27 The second array is: 1 2 6 3 9 5
  • 14. Using Two-Dimensional and Multidimensional Arrays One-dimensional or single-dimensional array Picture as column of values Elements accessed using single subscript Two-dimensional arrays Two or more columns of values Rows and columns Use two subscripts Matrix or table int[][] someNumbers = new int[3][4];
  • 15. View of a Two-Dimensional Array in Memory
  • 16. Using Two-Dimensional and Multidimensional Arrays (continued) int[][] rents = { {400, 450, 510}, {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600} }; public static void displayScores(int[][]scoresArray)
  • 17. Using Two-Dimensional and Multidimensional Arrays (continued) Multidimensional arrays More than two dimensions Create arrays of any size Keep track of order of variables needed as subscripts Don’t exhaust computer’s memory