SlideShare a Scribd company logo
Java Array



             1
Agenda
●   What is an array
●   Declaration of an array
●   Instantiation of an array
●   Accessing array element
●   Array length
●   Multi-dimensional array




                                  2
What is an Array?

                    3
Introduction to Arrays
●   Suppose we have here three variables of type int with
    different identifiers for each variable.
       int number1;
       int number2;
       int number3;

       number1 = 1;
       number2 = 2;
       number3 = 3;

    As you can see, it seems like a tedious task in order to just
    initialize and use the variables especially if they are used for
    the same purpose.


                                                                       4
Introduction to Arrays
●   In Java and other programming languages, there is one
    capability wherein we can use one variable to store a list of
    data and manipulate them more efficiently. This type of
    variable is called an array.

●   An array stores multiple data items of the same data type, in
    a contiguous block of memory, divided into a number of
    slots.




                                                                    5
Declaration of
  an Array
                 6
Declaring Arrays
●   To declare an array, write the data type, followed by a set of
    square brackets[], followed by the identifier name.

●   For example,
         int []ages;
    or
         int ages[];




                                                                     7
Instantiation of
   an Array
                   8
Array Instantiation
●   After declaring, we must create the array and specify its
    length with a constructor statement.

●   Definitions:
     –   Instantiation
           ●   In Java, this means creation

     –   Constructor
           ●   In order to instantiate an object, we need to use a constructor for this. A
               constructor is a method that is called to create a certain object.
           ●   We will cover more about instantiating objects and constructors later.




                                                                                             9
Array Instantiation
●   To instantiate (or create) an array, write the new keyword,
    followed by the square brackets containing the number of
    elements you want the array to have.
●   For example,
       //declaration
        int ages[];

       //instantiate object
       ages = new int[100];

    or, can also be written as,
       //declare and instantiate object
       int ages[] = new int[100];




                                                                  10
Array Instantiation




                      11
Array Instantiation
●   You can also instantiate an array by directly initializing it with
    data.

●   For example,
       int arr[] = {1, 2, 3, 4, 5};

    This statement declares and instantiates an array of integers
    with five elements (initialized to the values 1, 2, 3, 4, and 5).




                                                                         12
Sample Program
1    //creates an array of boolean variables with identifier
2    //results. This array contains 4 elements that are
3    //initialized to values {true, false, true, false}
4
5    boolean results[] = { true, false, true, false };
6
7    //creates an array of 4 double variables initialized
8    //to the values {100, 90, 80, 75};
9
10   double []grades = {100, 90, 80, 75};
11
12   //creates an array of Strings with identifier days and
13   //initialized. This array contains 7 elements
14
15   String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”,
     “Sun”};




                                                                   13
Accessing Array
   Element
                  14
Accessing an Array Element
●   To access an array element, or a part of the array, you use
    a number called an index or a subscript.

●   index number or subscript
     –   assigned to each member of the array, to allow the program to
         access an individual member of the array.
     –   begins with zero and progress sequentially by whole numbers to the
         end of the array.
     –   NOTE: Elements inside your array are from 0 to (sizeOfArray-1).




                                                                              15
Accessing an Array Element
●   For example, given the array we declared a while ago, we
    have
       //assigns 10 to the first element in the array
       ages[0] = 10;

       //prints the last element in the array
       System.out.print(ages[99]);




                                                               16
Accessing an Array Element
●   NOTE:
    –   once an array is declared and constructed, the stored value of each
        member of the array will be initialized to zero for number data.
    –   for reference data types such as Strings, they are NOT initialized to
        blanks or an empty string “”. Therefore, you must populate the String
        arrays explicitly.




                                                                                17
Accessing an Array Element
●   The following is a sample code on how to print all the
    elements in the array. This uses a for loop, so our code is
    shorter.
    1   public class ArraySample{
    2      public static void main( String[] args ){
    3         int[] ages = new int[100];
    4         for( int i=0; i<100; i++ ){
    5            System.out.print( ages[i] );
    6         }
    7      }
    8   }




                                                                  18
Coding Guidelines
1. It is usually better to initialize or instantiate the
  array right away after you declare it. For example,
  the declaration,

     int []arr = new int[100];

  is preferred over,

     int []arr;
     arr = new int[100];




                                                           19
Coding Guidelines
2. The elements of an n-element array have indexes
  from 0 to n-1. Note that there is no array element
  arr[n]! This will result in an array-index-out-of-
  bounds exception.

3. Remember: You cannot resize an array.




                                                       20
Array Length

               21
Array Length
●   In order to get the number of elements in an array, you can
    use the length field of an array.

●   The length field of an array returns the size of the array. It
    can be used by writing,
                         arrayName.length




                                                                     22
Array Length
1   public class ArraySample {
2      public static void main( String[] args ){
3         int[] ages = new int[100];
4
5           for( int i=0; i<ages.length; i++ ){
6              System.out.print( ages[i] );
7           }
8       }
9   }




                                                   23
Coding Guidelines
1. When creating for loops to process the elements of an
   array, use the array object's length field in the condition
   statement of the for loop. This will allow the loop to adjust
   automatically for different-sized arrays.


2. Declare the sizes of arrays in a Java program using named
   constants to make them easy to change. For example,

  final int ARRAY_SIZE = 1000; //declare a constant
  . . .
  int[] ages = new int[ARRAY_SIZE];




                                                                   24
Multi-Dimensional
      Array
                    25
Multidimensional Arrays
●   Multidimensional arrays are implemented as arrays of
    arrays.

●   Multidimensional arrays are declared by appending the
    appropriate number of bracket pairs after the array name.




                                                                26
Multidimensional Arrays
●   For example,
    // integer array 512 x 128 elements
    int[][] twoD = new int[512][128];

    // character array 8 x 16 x 24
    char[][][] threeD = new char[8][16][24];

    // String array 4 rows x 2 columns
    String[][] dogs = {{ "terry", "brown" },
                       { "Kristin", "white" },
                       { "toby", "gray"},
                       { "fido", "black"}
                      };




                                                 27
Multidimensional Arrays
●   To access an element in a multidimensional array is just the
    same as accessing the elements in a one dimensional array.

●   For example, to access the first element in the first row of
    the array dogs, we write,

       System.out.print( dogs[0][0] );

    This will print the String "terry" on the screen.




                                                                   28
Summary
●   Arrays
    –   Definition
    –   Declaration
    –   Instantiation and constructors (brief overview – to be discussed
        more later)
    –   Accessing an element
    –   The length field
    –   Multidimensional Arrays




                                                                           29

More Related Content

PDF
Module7
Seid Hussein
 
PDF
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PDF
intorduction to Arrays in java
Muthukumaran Subramanian
 
PPT
Arrays Class presentation
Neveen Reda
 
PPT
Lec 25 - arrays-strings
Princess Sam
 
PDF
Java Arrays
OXUS 20
 
PPT
Java Arrays
Jussi Pohjolainen
 
Module7
Seid Hussein
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
intorduction to Arrays in java
Muthukumaran Subramanian
 
Arrays Class presentation
Neveen Reda
 
Lec 25 - arrays-strings
Princess Sam
 
Java Arrays
OXUS 20
 
Java Arrays
Jussi Pohjolainen
 

What's hot (20)

PPTX
Array lecture
Joan Saño
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PPTX
Arrays in Java
Abhilash Nair
 
PPTX
Arrays in java
bhavesh prakash
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
PDF
An Introduction to Programming in Java: Arrays
Martin Chapman
 
PPT
Array in Java
Shehrevar Davierwala
 
PPTX
Arrays basics
sudhirvegad
 
PPT
Cso gaddis java_chapter8
mlrbrown
 
PPTX
Arrays C#
Raghuveer Guthikonda
 
PPTX
Array in C# 3.5
Gopal Ji Singh
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Arrays in java language
Hareem Naz
 
PPTX
Array in c++
Mahesha Mano
 
PPTX
Array in c language
home
 
PPTX
Java arrays
Mohammed Sikander
 
PPTX
Array in c#
Prem Kumar Badri
 
PPTX
Array in c language
umesh patil
 
PDF
Sql server difference faqs- 9
Umar Ali
 
Array lecture
Joan Saño
 
An introduction to scala
Mohsen Zainalpour
 
Arrays in Java
Abhilash Nair
 
Arrays in java
bhavesh prakash
 
Java: Introduction to Arrays
Tareq Hasan
 
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Array in Java
Shehrevar Davierwala
 
Arrays basics
sudhirvegad
 
Cso gaddis java_chapter8
mlrbrown
 
Array in C# 3.5
Gopal Ji Singh
 
Arrays in Java
Naz Abdalla
 
Arrays in java language
Hareem Naz
 
Array in c++
Mahesha Mano
 
Array in c language
home
 
Java arrays
Mohammed Sikander
 
Array in c#
Prem Kumar Badri
 
Array in c language
umesh patil
 
Sql server difference faqs- 9
Umar Ali
 
Ad

Similar to javaarray (20)

PDF
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
PPTX
Arrays in programming
TaseerRao
 
PPT
ch06.ppt
ansariparveen06
 
PPT
ch06.ppt
chandrasekar529044
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
array Details
shivas379526
 
PPT
JavaYDL6
Terry Yoast
 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
PPTX
Chapter6 (4) (1).pptx plog fix down more
mohammadalali41
 
PPS
Java session04
Niit Care
 
PPTX
Generative Coding Lecture notes using coding
ssuserff773c
 
PPT
Comp102 lec 8
Fraz Bakhsh
 
PDF
Arrays Java
Jose Sumba
 
PPTX
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
PDF
Lecture 3 Arrays on object oriented programming language
tanyakhathuria06
 
PDF
Week06
hccit
 
PPTX
Chapter 7.1
sotlsoc
 
PDF
Arrays a detailed explanation and presentation
riazahamed37
 
PDF
Array
Scott Donald
 
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Arrays in programming
TaseerRao
 
ch06.ppt
ansariparveen06
 
ch06.ppt
AqeelAbbas94
 
array Details
shivas379526
 
JavaYDL6
Terry Yoast
 
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Chapter6 (4) (1).pptx plog fix down more
mohammadalali41
 
Java session04
Niit Care
 
Generative Coding Lecture notes using coding
ssuserff773c
 
Comp102 lec 8
Fraz Bakhsh
 
Arrays Java
Jose Sumba
 
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
Lecture 3 Arrays on object oriented programming language
tanyakhathuria06
 
Week06
hccit
 
Chapter 7.1
sotlsoc
 
Arrays a detailed explanation and presentation
riazahamed37
 
Ad

More from Arjun Shanka (20)

PDF
Asp.net w3schools
Arjun Shanka
 
PDF
Php tutorial(w3schools)
Arjun Shanka
 
PDF
Sms several papers
Arjun Shanka
 
PDF
Jun 2012(1)
Arjun Shanka
 
PDF
System simulation 06_cs82
Arjun Shanka
 
PDF
javaexceptions
Arjun Shanka
 
PDF
javainheritance
Arjun Shanka
 
PDF
javarmi
Arjun Shanka
 
PDF
java-06inheritance
Arjun Shanka
 
PDF
hibernate
Arjun Shanka
 
PDF
javapackage
Arjun Shanka
 
PDF
swingbasics
Arjun Shanka
 
PDF
spring-tutorial
Arjun Shanka
 
PDF
struts
Arjun Shanka
 
PDF
javathreads
Arjun Shanka
 
PDF
javabeans
Arjun Shanka
 
PPT
72185-26528-StrutsMVC
Arjun Shanka
 
PDF
javanetworking
Arjun Shanka
 
PDF
javaiostream
Arjun Shanka
 
PDF
servlets
Arjun Shanka
 
Asp.net w3schools
Arjun Shanka
 
Php tutorial(w3schools)
Arjun Shanka
 
Sms several papers
Arjun Shanka
 
Jun 2012(1)
Arjun Shanka
 
System simulation 06_cs82
Arjun Shanka
 
javaexceptions
Arjun Shanka
 
javainheritance
Arjun Shanka
 
javarmi
Arjun Shanka
 
java-06inheritance
Arjun Shanka
 
hibernate
Arjun Shanka
 
javapackage
Arjun Shanka
 
swingbasics
Arjun Shanka
 
spring-tutorial
Arjun Shanka
 
struts
Arjun Shanka
 
javathreads
Arjun Shanka
 
javabeans
Arjun Shanka
 
72185-26528-StrutsMVC
Arjun Shanka
 
javanetworking
Arjun Shanka
 
javaiostream
Arjun Shanka
 
servlets
Arjun Shanka
 

Recently uploaded (20)

PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
 
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
CIFDAQ
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 

javaarray

  • 2. Agenda ● What is an array ● Declaration of an array ● Instantiation of an array ● Accessing array element ● Array length ● Multi-dimensional array 2
  • 3. What is an Array? 3
  • 4. Introduction to Arrays ● Suppose we have here three variables of type int with different identifiers for each variable. int number1; int number2; int number3; number1 = 1; number2 = 2; number3 = 3; As you can see, it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. 4
  • 5. Introduction to Arrays ● In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. This type of variable is called an array. ● An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots. 5
  • 6. Declaration of an Array 6
  • 7. Declaring Arrays ● To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name. ● For example, int []ages; or int ages[]; 7
  • 8. Instantiation of an Array 8
  • 9. Array Instantiation ● After declaring, we must create the array and specify its length with a constructor statement. ● Definitions: – Instantiation ● In Java, this means creation – Constructor ● In order to instantiate an object, we need to use a constructor for this. A constructor is a method that is called to create a certain object. ● We will cover more about instantiating objects and constructors later. 9
  • 10. Array Instantiation ● To instantiate (or create) an array, write the new keyword, followed by the square brackets containing the number of elements you want the array to have. ● For example, //declaration int ages[]; //instantiate object ages = new int[100]; or, can also be written as, //declare and instantiate object int ages[] = new int[100]; 10
  • 12. Array Instantiation ● You can also instantiate an array by directly initializing it with data. ● For example, int arr[] = {1, 2, 3, 4, 5}; This statement declares and instantiates an array of integers with five elements (initialized to the values 1, 2, 3, 4, and 5). 12
  • 13. Sample Program 1 //creates an array of boolean variables with identifier 2 //results. This array contains 4 elements that are 3 //initialized to values {true, false, true, false} 4 5 boolean results[] = { true, false, true, false }; 6 7 //creates an array of 4 double variables initialized 8 //to the values {100, 90, 80, 75}; 9 10 double []grades = {100, 90, 80, 75}; 11 12 //creates an array of Strings with identifier days and 13 //initialized. This array contains 7 elements 14 15 String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”}; 13
  • 14. Accessing Array Element 14
  • 15. Accessing an Array Element ● To access an array element, or a part of the array, you use a number called an index or a subscript. ● index number or subscript – assigned to each member of the array, to allow the program to access an individual member of the array. – begins with zero and progress sequentially by whole numbers to the end of the array. – NOTE: Elements inside your array are from 0 to (sizeOfArray-1). 15
  • 16. Accessing an Array Element ● For example, given the array we declared a while ago, we have //assigns 10 to the first element in the array ages[0] = 10; //prints the last element in the array System.out.print(ages[99]); 16
  • 17. Accessing an Array Element ● NOTE: – once an array is declared and constructed, the stored value of each member of the array will be initialized to zero for number data. – for reference data types such as Strings, they are NOT initialized to blanks or an empty string “”. Therefore, you must populate the String arrays explicitly. 17
  • 18. Accessing an Array Element ● The following is a sample code on how to print all the elements in the array. This uses a for loop, so our code is shorter. 1 public class ArraySample{ 2 public static void main( String[] args ){ 3 int[] ages = new int[100]; 4 for( int i=0; i<100; i++ ){ 5 System.out.print( ages[i] ); 6 } 7 } 8 } 18
  • 19. Coding Guidelines 1. It is usually better to initialize or instantiate the array right away after you declare it. For example, the declaration, int []arr = new int[100]; is preferred over, int []arr; arr = new int[100]; 19
  • 20. Coding Guidelines 2. The elements of an n-element array have indexes from 0 to n-1. Note that there is no array element arr[n]! This will result in an array-index-out-of- bounds exception. 3. Remember: You cannot resize an array. 20
  • 22. Array Length ● In order to get the number of elements in an array, you can use the length field of an array. ● The length field of an array returns the size of the array. It can be used by writing, arrayName.length 22
  • 23. Array Length 1 public class ArraySample { 2 public static void main( String[] args ){ 3 int[] ages = new int[100]; 4 5 for( int i=0; i<ages.length; i++ ){ 6 System.out.print( ages[i] ); 7 } 8 } 9 } 23
  • 24. Coding Guidelines 1. When creating for loops to process the elements of an array, use the array object's length field in the condition statement of the for loop. This will allow the loop to adjust automatically for different-sized arrays. 2. Declare the sizes of arrays in a Java program using named constants to make them easy to change. For example, final int ARRAY_SIZE = 1000; //declare a constant . . . int[] ages = new int[ARRAY_SIZE]; 24
  • 25. Multi-Dimensional Array 25
  • 26. Multidimensional Arrays ● Multidimensional arrays are implemented as arrays of arrays. ● Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. 26
  • 27. Multidimensional Arrays ● For example, // integer array 512 x 128 elements int[][] twoD = new int[512][128]; // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24]; // String array 4 rows x 2 columns String[][] dogs = {{ "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"}, { "fido", "black"} }; 27
  • 28. Multidimensional Arrays ● To access an element in a multidimensional array is just the same as accessing the elements in a one dimensional array. ● For example, to access the first element in the first row of the array dogs, we write, System.out.print( dogs[0][0] ); This will print the String "terry" on the screen. 28
  • 29. Summary ● Arrays – Definition – Declaration – Instantiation and constructors (brief overview – to be discussed more later) – Accessing an element – The length field – Multidimensional Arrays 29