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

PPTX
lec 2- array declaration and initialization.pptx
PDF
An Introduction to Programming in Java: Arrays
PPTX
Arrays in java language
PPT
One Dimensional Array
PDF
Lecture-2(2): Number System & Conversion
PPTX
Structure in C language
PPTX
Programming in c Arrays
lec 2- array declaration and initialization.pptx
An Introduction to Programming in Java: Arrays
Arrays in java language
One Dimensional Array
Lecture-2(2): Number System & Conversion
Structure in C language
Programming in c Arrays

What's hot (20)

PPT
Array in Java
PPTX
Stack using Linked List
PPT
PPT
One dimensional 2
PDF
Strings IN C
PPTX
Introduction to data structure and algorithms
PPTX
C Programming: Structure and Union
PPT
PPTX
PPT
Java Arrays
PPTX
Pointer arithmetic in c
PPTX
Arrays in c
PDF
Pointers and Structures
PPSX
C Programming : Arrays
PPTX
Array in c programming
PDF
Namespaces
PPTX
Sparse matrix
PDF
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
PPTX
Structure in C
PPTX
Array ppt
Array in Java
Stack using Linked List
One dimensional 2
Strings IN C
Introduction to data structure and algorithms
C Programming: Structure and Union
Java Arrays
Pointer arithmetic in c
Arrays in c
Pointers and Structures
C Programming : Arrays
Array in c programming
Namespaces
Sparse matrix
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
Structure in C
Array ppt
Ad

Similar to Java: Introduction to Arrays (20)

PPT
Data Structure Midterm Lesson Arrays
PDF
Arrays and library functions
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
PDF
ARRAYS
PDF
Arrays-Computer programming
PPT
Arrays and vectors in Data Structure.ppt
PPTX
Lecture 1 mte 407
PPTX
Lecture 1 mte 407
PDF
C sharp chap6
PPTX
6_Array.pptx
PPTX
Array and its operation in C programming
PPTX
Intro to C# - part 2.pptx emerging technology
PDF
Introduction to Arrays in C
DOCX
Array assignment
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
PPTX
Chapter 13.pptx
PDF
Arrays and library functions
PPTX
object oriented programing in python and pip
PDF
Array
Data Structure Midterm Lesson Arrays
Arrays and library functions
Homework Assignment – Array Technical DocumentWrite a technical .pdf
ARRAYS
Arrays-Computer programming
Arrays and vectors in Data Structure.ppt
Lecture 1 mte 407
Lecture 1 mte 407
C sharp chap6
6_Array.pptx
Array and its operation in C programming
Intro to C# - part 2.pptx emerging technology
Introduction to Arrays in C
Array assignment
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
Chapter 13.pptx
Arrays and library functions
object oriented programing in python and pip
Array
Ad

More from Tareq Hasan (20)

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

Recently uploaded (20)

PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
01-Introduction-to-Information-Management.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Microbial diseases, their pathogenesis and prophylaxis
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
VCE English Exam - Section C Student Revision Booklet
01-Introduction-to-Information-Management.pdf
TR - Agricultural Crops Production NC III.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Anesthesia in Laparoscopic Surgery in India
human mycosis Human fungal infections are called human mycosis..pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Pre independence Education in Inndia.pdf
Microbial disease of the cardiovascular and lymphatic systems
Microbial diseases, their pathogenesis and prophylaxis

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