SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
1
Object Oriented Programming
FIEC ESPOL
Arrays
Creating and Accessing Arrays
• An array can be created using one statement
double[] score = new double[5];
• Or using two statements:
double[] score;double[] score;
score = new double[5];
– The first statement declares score an array of
doubles
– The second statement creates an array and makes
the variable score a name for the array
2
Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
Declaring and Creating an Array
• An array is declared and created in almost the
same way that objects are declared and created:
BaseType[] ArrayName = new BaseType[size];
– The size may be given as an expression that
l t t ti i t f levaluates to a nonnegative integer, for example, an
int variable
char[] line = new char[80];
double[] reading = new double[count];
Person[] specimen = new Person[100];
3
Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
Three Ways to Use Square Brackets [] with
an Array Name
• Square brackets can be used to create a type
name:
double[] score;
• Square brackets can be used with an integerq g
value as part of the special syntax Java uses to
create a new array:
score = new double[5];
• Square brackets can be used to name an
indexed variable of an array:
max = score[0];
4
Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
2
The length Instance Variable
• An array is considered to be an object
• Every array has exactly one instance variable
named length
d bl [] di d bl [100]
5Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
double[] reading = new double[100];
for (int index = 0; index < reading.length; index++)
{
reading[index] = 42.0;
}
An Array of Characters Is Not a String
• The class String has a constructor that has a
single parameter of type char[]
String s = new String(a);
– The object s will have the same sequence of
characters as the entire array a ("ABC"), but is ancharacters as the entire array a ( ABC ), but is an
independent copy
• Another String constructor uses a subrange of
a character array instead
String s2 = new String(a,0,2);
– Given a as before, the new string object is "AB“
(continued)
6Copyright © 2008 Pearson Addison‐Wesley.
All rights reserved
An Array of Characters Is Not a String
• An array of characters does have some
things in common with String objects
– For example, an array of characters can be
output using println
System.out.println(a);
– Given a as before, this would produce the
output
ABC
7
Copyright © 2008 Pearson Addison‐Wesley.
All rights reserved
Arrays and References
• Like class types, a variable of an array
type holds a reference
– Arrays are objects
A variable of an array type holds the address– A variable of an array type holds the address
of where the array object is stored in memory
– Array types are (usually) considered to be
class types
8Copyright © 2008 Pearson Addison‐Wesley
. All rights reserved
3
Arrays with a Class Base Type
• The base type of an array can be a class type
Date[] holidayList = new Date[20];
• The above example creates 20 indexed
reference variables of type Date. It does notyp
create 20 objects of the class Date
– Each of these indexed variables are automatically
initialized to null
– Any attempt to reference any them at this point would
result in a "null pointer exception" error message
(continued)
9Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
Arrays with a Class Base Type
• Like any other object, each of the indexed variables
requires a separate invocation of a constructor using
new (singly, or perhaps using a for loop) to create an
object to reference
holidayList[0] = new Date();y [ ] ();
. . .
holidayList[19] = new Date();
OR
for (int i = 0; i < holidayList.length; i++)
holidayList[i] = new Date();
• Each of the indexed variables can now be referenced
since each holds the memory address of a Date object
10Copyright © 2008 Pearson Addison‐Wesley.
All rights reserved
Arguments for the Method main
• The heading for the main method of a program
has a parameter for an array of String
– It is usually called args by convention
public static void main(String[] args)
– Note that since args is a parameter it could be
11
Note that since args is a parameter, it could be
replaced by any other non-keyword identifier
• If a Java program is run without giving an
argument to main, then a default empty array of
strings is automatically provided
Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
Arguments for the Method main
• If a program requires that the main
method be provided an array of strings
argument, each element must be provided
from the command line when the program
12
from the command line when the program
is run
java SomeProgram Hi ! there
– This will set args[0] to "Hi", args[1] to "!",
and args[2] to "there"
– It will also set args.length to 3
Copyright © 2008 Pearson Addison‐Wesley
All rights reserved
4
Multidimensional Arrays
• It is sometimes useful to have an array with
more than one index
• Multidimensional arrays are declared and
created in basically the same way as one-
dimensional arrays
Aug 6, 2007 16
y
– You simply use as many square brackets as there are
indices
– Each index must be enclosed in its own brackets
double[][]table = new double[100][10];
int[][][] figure = new int[10][20][30];
Person[][] = new Person[10][100];
Copyright © 2008 Pearson Addison‐Wesley. 
All rights reserved
Multidimensional Arrays
• Multidimensional arrays may have any number
of indices, but perhaps the most common
number is two
– Two-dimensional array can be visualized as a two-
dimensional display with the first index giving the row
Aug 6, 2007 17
dimensional display with the first index giving the row,
and the second index giving the column
char[][] a = new char[5][12];
– Note that, like a one-dimensional array, each element
of a multidimensional array is just a variable of the
base type (in this case, char)
Copyright © 2008 Pearson Addison‐Wesley.
All rights reserved
Using the length Instance Variable
• The following program demonstrates how a
nested for loop can be used to process a
two-dimensional array
– Note how each length instance variable is used
int row, column;
for (row = 0; row < page.length; row++)
for (column = 0; column < page[row].length;
column++)
page[row][column] = 'Z';
Copyright © 2008 Pearson Addison‐Wesley.
All rights reserved

Contenu connexe

Tendances

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysMartin Chapman
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT LATHA LAKSHMI
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Abou Bakr Ashraf
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array PointerTareq Hasan
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrayschauhankapil
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in phpKamal Acharya
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Array
ArrayArray
ArrayHajar
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array dincyjain
 

Tendances (20)

An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
Arrays in C++ in Tamil - TNSCERT SYLLABUS PPT
 
Lesson 11 one dimensional array
Lesson 11 one dimensional arrayLesson 11 one dimensional array
Lesson 11 one dimensional array
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Visula C# Programming Lecture 5
Visula C# Programming Lecture 5Visula C# Programming Lecture 5
Visula C# Programming Lecture 5
 
02 c++ Array Pointer
02 c++ Array Pointer02 c++ Array Pointer
02 c++ Array Pointer
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
2 arrays
2   arrays2   arrays
2 arrays
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
 
Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Working with arrays in php
Working with arrays in phpWorking with arrays in php
Working with arrays in php
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Array lecture
Array lectureArray lecture
Array lecture
 
Array
ArrayArray
Array
 
Array in Java
Array in JavaArray in Java
Array in Java
 
One Dimensional Array
One Dimensional Array One Dimensional Array
One Dimensional Array
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Array
ArrayArray
Array
 

En vedette

Sun, Moon and Planets Slideshow
Sun, Moon and Planets SlideshowSun, Moon and Planets Slideshow
Sun, Moon and Planets Slideshowsanstanton
 
Punctuation marks
Punctuation marksPunctuation marks
Punctuation marksewaszolek
 
Punctuation
PunctuationPunctuation
PunctuationOKate321
 
Punctuation Powerpoint
Punctuation PowerpointPunctuation Powerpoint
Punctuation Powerpointconno1ej
 
The Solar System Powerpoint
The Solar System PowerpointThe Solar System Powerpoint
The Solar System Powerpointoliverh
 

En vedette (7)

6 plus 1 traits
6 plus 1 traits6 plus 1 traits
6 plus 1 traits
 
Sun, Moon and Planets Slideshow
Sun, Moon and Planets SlideshowSun, Moon and Planets Slideshow
Sun, Moon and Planets Slideshow
 
Punctuation marks
Punctuation marksPunctuation marks
Punctuation marks
 
Punctuation
PunctuationPunctuation
Punctuation
 
Punctuation
PunctuationPunctuation
Punctuation
 
Punctuation Powerpoint
Punctuation PowerpointPunctuation Powerpoint
Punctuation Powerpoint
 
The Solar System Powerpoint
The Solar System PowerpointThe Solar System Powerpoint
The Solar System Powerpoint
 

Similaire à Arrays Java

Similaire à Arrays Java (20)

Chapter 6 Absolute Java
Chapter 6 Absolute JavaChapter 6 Absolute Java
Chapter 6 Absolute Java
 
Chap6java5th
Chap6java5thChap6java5th
Chap6java5th
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
array Details
array Detailsarray Details
array Details
 
Arrays
ArraysArrays
Arrays
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
Learn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & ArraysLearn C# Programming - Nullables & Arrays
Learn C# Programming - Nullables & Arrays
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Generative Coding Lecture notes using coding
Generative Coding Lecture notes using codingGenerative Coding Lecture notes using coding
Generative Coding Lecture notes using coding
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Eo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5eEo gaddis java_chapter_07_5e
Eo gaddis java_chapter_07_5e
 
C
CC
C
 
PHP array 1
PHP array 1PHP array 1
PHP array 1
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 

Dernier

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 

Dernier (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 

Arrays Java

  • 1. 1 Object Oriented Programming FIEC ESPOL Arrays Creating and Accessing Arrays • An array can be created using one statement double[] score = new double[5]; • Or using two statements: double[] score;double[] score; score = new double[5]; – The first statement declares score an array of doubles – The second statement creates an array and makes the variable score a name for the array 2 Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved Declaring and Creating an Array • An array is declared and created in almost the same way that objects are declared and created: BaseType[] ArrayName = new BaseType[size]; – The size may be given as an expression that l t t ti i t f levaluates to a nonnegative integer, for example, an int variable char[] line = new char[80]; double[] reading = new double[count]; Person[] specimen = new Person[100]; 3 Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved Three Ways to Use Square Brackets [] with an Array Name • Square brackets can be used to create a type name: double[] score; • Square brackets can be used with an integerq g value as part of the special syntax Java uses to create a new array: score = new double[5]; • Square brackets can be used to name an indexed variable of an array: max = score[0]; 4 Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved
  • 2. 2 The length Instance Variable • An array is considered to be an object • Every array has exactly one instance variable named length d bl [] di d bl [100] 5Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved double[] reading = new double[100]; for (int index = 0; index < reading.length; index++) { reading[index] = 42.0; } An Array of Characters Is Not a String • The class String has a constructor that has a single parameter of type char[] String s = new String(a); – The object s will have the same sequence of characters as the entire array a ("ABC"), but is ancharacters as the entire array a ( ABC ), but is an independent copy • Another String constructor uses a subrange of a character array instead String s2 = new String(a,0,2); – Given a as before, the new string object is "AB“ (continued) 6Copyright © 2008 Pearson Addison‐Wesley. All rights reserved An Array of Characters Is Not a String • An array of characters does have some things in common with String objects – For example, an array of characters can be output using println System.out.println(a); – Given a as before, this would produce the output ABC 7 Copyright © 2008 Pearson Addison‐Wesley. All rights reserved Arrays and References • Like class types, a variable of an array type holds a reference – Arrays are objects A variable of an array type holds the address– A variable of an array type holds the address of where the array object is stored in memory – Array types are (usually) considered to be class types 8Copyright © 2008 Pearson Addison‐Wesley . All rights reserved
  • 3. 3 Arrays with a Class Base Type • The base type of an array can be a class type Date[] holidayList = new Date[20]; • The above example creates 20 indexed reference variables of type Date. It does notyp create 20 objects of the class Date – Each of these indexed variables are automatically initialized to null – Any attempt to reference any them at this point would result in a "null pointer exception" error message (continued) 9Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved Arrays with a Class Base Type • Like any other object, each of the indexed variables requires a separate invocation of a constructor using new (singly, or perhaps using a for loop) to create an object to reference holidayList[0] = new Date();y [ ] (); . . . holidayList[19] = new Date(); OR for (int i = 0; i < holidayList.length; i++) holidayList[i] = new Date(); • Each of the indexed variables can now be referenced since each holds the memory address of a Date object 10Copyright © 2008 Pearson Addison‐Wesley. All rights reserved Arguments for the Method main • The heading for the main method of a program has a parameter for an array of String – It is usually called args by convention public static void main(String[] args) – Note that since args is a parameter it could be 11 Note that since args is a parameter, it could be replaced by any other non-keyword identifier • If a Java program is run without giving an argument to main, then a default empty array of strings is automatically provided Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved Arguments for the Method main • If a program requires that the main method be provided an array of strings argument, each element must be provided from the command line when the program 12 from the command line when the program is run java SomeProgram Hi ! there – This will set args[0] to "Hi", args[1] to "!", and args[2] to "there" – It will also set args.length to 3 Copyright © 2008 Pearson Addison‐Wesley All rights reserved
  • 4. 4 Multidimensional Arrays • It is sometimes useful to have an array with more than one index • Multidimensional arrays are declared and created in basically the same way as one- dimensional arrays Aug 6, 2007 16 y – You simply use as many square brackets as there are indices – Each index must be enclosed in its own brackets double[][]table = new double[100][10]; int[][][] figure = new int[10][20][30]; Person[][] = new Person[10][100]; Copyright © 2008 Pearson Addison‐Wesley.  All rights reserved Multidimensional Arrays • Multidimensional arrays may have any number of indices, but perhaps the most common number is two – Two-dimensional array can be visualized as a two- dimensional display with the first index giving the row Aug 6, 2007 17 dimensional display with the first index giving the row, and the second index giving the column char[][] a = new char[5][12]; – Note that, like a one-dimensional array, each element of a multidimensional array is just a variable of the base type (in this case, char) Copyright © 2008 Pearson Addison‐Wesley. All rights reserved Using the length Instance Variable • The following program demonstrates how a nested for loop can be used to process a two-dimensional array – Note how each length instance variable is used int row, column; for (row = 0; row < page.length; row++) for (column = 0; column < page[row].length; column++) page[row][column] = 'Z'; Copyright © 2008 Pearson Addison‐Wesley. All rights reserved