SlideShare uma empresa Scribd logo
1 de 4
Baixar para ler offline
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

6. ARRAYS
An array is a container object that holds a fixed number of values of a single type. The length
of an array is established when the array is created. After creation, its length is fixed. You've
seen an example of arrays already, in the main method of the "Hello World!" application.

An array
elements

of

ten

Each item in an array is called an element, and each element is accessed by its numerical
index. As shown in the above illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in it, and
prints each value to standard output.
class ArrayDemo
{
public static void main(String[] args)
{
int[] anArray;
// declares an array of integers
anArray = new int[10];
anArray[0]
anArray[1]
anArray[2]
anArray[3]
anArray[4]
anArray[5]
anArray[6]
anArray[7]
anArray[8]
anArray[9]

=
=
=
=
=
=
=
=
=
=

// allocates memory for 10 integers

100; // initialize first element
200; // initialize second element
300; // etc.
400;
500;
600;
700;
800;
900;
1000;

System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element
System.out.println("Element

at
at
at
at
at
at
at
at
at
at

index
index
index
index
index
index
index
index
index
index

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

"
"
"
"
"
"
"
"
"
"

+
+
+
+
+
+
+
+
+
+

anArray[0]);
anArray[1]);
anArray[2]);
anArray[3]);
anArray[4]);
anArray[5]);
anArray[6]);
anArray[7]);
anArray[8]);
anArray[9]);

}
}

The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300

Java - Chapter 6

Page 1 of 4
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

The Java Programming Language
Element
Element
Element
Element
Element
Element
Element

at
at
at
at
at
at
at

index
index
index
index
index
index
index

3:
4:
5:
6:
7:
8:
9:

400
500
600
700
800
900
1000

Declaring a Variable to Refer to an Array
The above program declares anArray with the following line of code:
int[] anArray;

// declares an array of integers

Like declarations for variables of other types, an array declaration has two components: the
array's type and the array's name. An array's type is written as type[], where type is the data
type of the contained elements; the square brackets are special symbols indicating that this
variable holds an array. The size of the array is not part of its type (which is why the brackets
are empty). An array's name can be anything you want, provided that it follows the rules and
conventions as previously discussed in the naming section. As with variables of other types,
the declaration does not actually create an array — it simply tells the compiler that this
variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byt e[ ] an Ar ra yO fB yt es ;
sho rt [] a nA rr ay Of Sh or ts ;
lon g[ ] an Ar ra yO fL on gs ;
flo at [] a nA rr ay Of Fl oa ts ;
dou bl e[ ] an Ar ra yO fD ou bl es ;
boo le an [] a nA rr ay Of Bo ol ea ns ;
cha r[ ] an Ar ra yO fC ha rs ;
Str in g[ ] an Ar ra yO fS tr in gs ;

You can also place the square brackets after the array's name:
float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; the brackets identify the array type and should
appear with the type designation.

Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator. The next statement in the ArrayDemo
program allocates an array with enough memory for ten integer elements and assigns the
array to the anArray variable.
anArray = new int[10];

// create an array of integers

If this statement were missing, the compiler would print an error like the following, and
compilation would fail:
ArrayDemo.java:4: Variable anArray may not have been initialized.

The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element

Page 2 of 4

Java - Chapter 6
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.
The Java Programming Language

anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.

Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);

Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Here the length of the array is determined by the number of values provided between { and }.
You can also declare an array of arrays (also known as a multidimensional array) by using
two or more sets of square brackets, such as String[][] names. Each element, therefore,
must be accessed by a corresponding number of index values.
In the Java programming language, a multidimensional array is simply an array whose
components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of
this is that the rows are allowed to vary in length, as shown in the following
MultiDimArrayDemo program:
class MultiDimArrayDemo {
public static void main(String[] args) {
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
System.out.println(names[0][0] + names[1][0]); //Mr. Smith
System.out.println(names[0][2] + names[1][1]); //Ms. Jones
}
}

The output from this program is:
Mr. Smith
Ms. Jones

Finally, you can use the built-in length property to determine the size of any array. The code
System.out.println(anArray.length);

will print the array's size to standard output.

Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from
one array into another:
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
The two Object arguments specify the array to copy from and the array to copy to. The three
int arguments specify the starting position in the source array, the starting position in the

destination array, and the number of array elements to copy.
The following program, ArrayCopyDemo, declares an array of char elements, spelling the
word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a
second array:
class ArrayCopyDemo {

Prof. Mukesh N Tekwani [mukeshnt@yahoo.com]

Page 3 of 4
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

The Java Programming Language
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

The output from this program is:
caffein

Questions
1.
2.
3.
4.

The term "instance variable" is another name for ___.
The term "class variable" is another name for ___.
A local variable stores temporary state; it is declared inside a ___.
A variable declared within the opening and closing parenthesis of a method signature
called a ____.
5. What are the eight primitive data types supported by the Java programming language?
6. Character strings are represented by the class ___.
7. An ___ is a container object that holds a fixed number of values of a single type.

Answers to Questions
1.
2.
3.
4.
5.
6.
7.

non-static field.
static field.
method.
parameter.
byte, short, int, long, float, double, boolean, char
java.lang.String.
array

Page 4 of 4

Java - Chapter 6

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Array in C# 3.5
Array in C# 3.5Array in C# 3.5
Array in C# 3.5
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
 
C# Arrays
C# ArraysC# Arrays
C# Arrays
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
LectureNotes-02-DSA
LectureNotes-02-DSALectureNotes-02-DSA
LectureNotes-02-DSA
 
Array lecture
Array lectureArray lecture
Array lecture
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Java execise
Java execiseJava execise
Java execise
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
C# Cheat Sheet
C# Cheat SheetC# Cheat Sheet
C# Cheat Sheet
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 

Destaque

Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQMukesh Tekwani
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsMukesh Tekwani
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingMukesh Tekwani
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1Mukesh Tekwani
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signalsMukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferWayne Jones Jnr
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programmingMukesh Tekwani
 

Destaque (18)

Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java misc1
Java misc1Java misc1
Java misc1
 
Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Html graphics
Html graphicsHtml graphics
Html graphics
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 

Semelhante a Java chapter 6 - Arrays -syntax and use

Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
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 arraysJayanthiM19
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docxPamarthi Kumar
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfajajkhan16
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
cprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptcprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptgeorgejustymirobi1
 
cprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptcprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptPrasanna657934
 

Semelhante a Java chapter 6 - Arrays -syntax and use (20)

Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Arrays in java.pptx
Arrays in java.pptxArrays in java.pptx
Arrays in java.pptx
 
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
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Arrays
ArraysArrays
Arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Array concept
Array conceptArray concept
Array concept
 
Arrays
ArraysArrays
Arrays
 
cprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptcprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.ppt
 
cprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.pptcprogrammingarrayaggregatetype.ppt
cprogrammingarrayaggregatetype.ppt
 

Mais de Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Mais de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Último

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 

Último (20)

ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 

Java chapter 6 - Arrays -syntax and use

  • 1. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. 6. ARRAYS An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. An array elements of ten Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. The following program, ArrayDemo, creates an array of integers, puts some values in it, and prints each value to standard output. class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; anArray[0] anArray[1] anArray[2] anArray[3] anArray[4] anArray[5] anArray[6] anArray[7] anArray[8] anArray[9] = = = = = = = = = = // allocates memory for 10 integers 100; // initialize first element 200; // initialize second element 300; // etc. 400; 500; 600; 700; 800; 900; 1000; System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element at at at at at at at at at at index index index index index index index index index index 0: 1: 2: 3: 4: 5: 6: 7: 8: 9: " " " " " " " " " " + + + + + + + + + + anArray[0]); anArray[1]); anArray[2]); anArray[3]); anArray[4]); anArray[5]); anArray[6]); anArray[7]); anArray[8]); anArray[9]); } } The output from this program is: Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Java - Chapter 6 Page 1 of 4
  • 2. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. The Java Programming Language Element Element Element Element Element Element Element at at at at at at at index index index index index index index 3: 4: 5: 6: 7: 8: 9: 400 500 600 700 800 900 1000 Declaring a Variable to Refer to an Array The above program declares anArray with the following line of code: int[] anArray; // declares an array of integers Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array — it simply tells the compiler that this variable will hold an array of the specified type. Similarly, you can declare arrays of other types: byt e[ ] an Ar ra yO fB yt es ; sho rt [] a nA rr ay Of Sh or ts ; lon g[ ] an Ar ra yO fL on gs ; flo at [] a nA rr ay Of Fl oa ts ; dou bl e[ ] an Ar ra yO fD ou bl es ; boo le an [] a nA rr ay Of Bo ol ea ns ; cha r[ ] an Ar ra yO fC ha rs ; Str in g[ ] an Ar ra yO fS tr in gs ; You can also place the square brackets after the array's name: float anArrayOfFloats[]; // this form is discouraged However, convention discourages this form; the brackets identify the array type and should appear with the type designation. Creating, Initializing, and Accessing an Array One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10]; // create an array of integers If this statement were missing, the compiler would print an error like the following, and compilation would fail: ArrayDemo.java:4: Variable anArray may not have been initialized. The next few lines assign values to each element of the array: anArray[0] = 100; // initialize first element Page 2 of 4 Java - Chapter 6
  • 3. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. The Java Programming Language anArray[1] = 200; // initialize second element anArray[2] = 300; // etc. Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]); Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; Here the length of the array is determined by the number of values provided between { and }. You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values. In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program: class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); //Mr. Smith System.out.println(names[0][2] + names[1][1]); //Ms. Jones } } The output from this program is: Mr. Smith Ms. Jones Finally, you can use the built-in length property to determine the size of any array. The code System.out.println(anArray.length); will print the array's size to standard output. Copying Arrays The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy. The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array: class ArrayCopyDemo { Prof. Mukesh N Tekwani [mukeshnt@yahoo.com] Page 3 of 4
  • 4. Generated by Foxit PDF Creator © Foxit Software http://www.foxitsoftware.com For evaluation only. The Java Programming Language public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } } The output from this program is: caffein Questions 1. 2. 3. 4. The term "instance variable" is another name for ___. The term "class variable" is another name for ___. A local variable stores temporary state; it is declared inside a ___. A variable declared within the opening and closing parenthesis of a method signature called a ____. 5. What are the eight primitive data types supported by the Java programming language? 6. Character strings are represented by the class ___. 7. An ___ is a container object that holds a fixed number of values of a single type. Answers to Questions 1. 2. 3. 4. 5. 6. 7. non-static field. static field. method. parameter. byte, short, int, long, float, double, boolean, char java.lang.String. array Page 4 of 4 Java - Chapter 6