SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PPT
Strings Arrays
phanleson
 
PDF
LectureNotes-06-DSA
Haitham El-Ghareeb
 
PPTX
Arrays C#
Raghuveer Guthikonda
 
PPT
Java: Introduction to Arrays
Tareq Hasan
 
PPTX
Array in C# 3.5
Gopal Ji Singh
 
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Philip Schwarz
 
PPTX
C# Arrays
Hock Leng PUAH
 
PDF
Java Arrays
OXUS 20
 
PDF
Array and Collections in c#
Umar Farooq
 
PDF
LectureNotes-02-DSA
Haitham El-Ghareeb
 
PPTX
Array lecture
Joan Saño
 
PPT
Lec 25 - arrays-strings
Princess Sam
 
PPTX
Arrays in java
bhavesh prakash
 
DOCX
Java execise
Keneth miles
 
PPTX
Arrays in Java
Abhilash Nair
 
PPTX
Datastructures in python
hydpy
 
PDF
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
PDF
C# Cheat Sheet
GlowTouch
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
PPTX
arrays of structures
arushi bhatnagar
 
Strings Arrays
phanleson
 
LectureNotes-06-DSA
Haitham El-Ghareeb
 
Java: Introduction to Arrays
Tareq Hasan
 
Array in C# 3.5
Gopal Ji Singh
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Philip Schwarz
 
C# Arrays
Hock Leng PUAH
 
Java Arrays
OXUS 20
 
Array and Collections in c#
Umar Farooq
 
LectureNotes-02-DSA
Haitham El-Ghareeb
 
Array lecture
Joan Saño
 
Lec 25 - arrays-strings
Princess Sam
 
Arrays in java
bhavesh prakash
 
Java execise
Keneth miles
 
Arrays in Java
Abhilash Nair
 
Datastructures in python
hydpy
 
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
C# Cheat Sheet
GlowTouch
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
arrays of structures
arushi bhatnagar
 

Viewers also liked (18)

PDF
Data Link Layer
Mukesh Tekwani
 
PDF
Java chapter 1
Mukesh Tekwani
 
PDF
Java misc1
Mukesh Tekwani
 
PDF
Java chapter 3
Mukesh Tekwani
 
PDF
Digital signal and image processing FAQ
Mukesh Tekwani
 
PDF
Java chapter 5
Mukesh Tekwani
 
PDF
Jdbc 1
Mukesh Tekwani
 
PDF
Python reading and writing files
Mukesh Tekwani
 
PDF
Java swing 1
Mukesh Tekwani
 
PDF
Html tables examples
Mukesh Tekwani
 
PDF
Html graphics
Mukesh Tekwani
 
PDF
Java 1-contd
Mukesh Tekwani
 
PDF
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
PDF
Phases of the Compiler - Systems Programming
Mukesh Tekwani
 
PDF
Data communications ch 1
Mukesh Tekwani
 
PDF
Chap 3 data and signals
Mukesh Tekwani
 
PPT
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
 
PDF
Introduction to systems programming
Mukesh Tekwani
 
Data Link Layer
Mukesh Tekwani
 
Java chapter 1
Mukesh Tekwani
 
Java misc1
Mukesh Tekwani
 
Java chapter 3
Mukesh Tekwani
 
Digital signal and image processing FAQ
Mukesh Tekwani
 
Java chapter 5
Mukesh Tekwani
 
Python reading and writing files
Mukesh Tekwani
 
Java swing 1
Mukesh Tekwani
 
Html tables examples
Mukesh Tekwani
 
Html graphics
Mukesh Tekwani
 
Java 1-contd
Mukesh Tekwani
 
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
Phases of the Compiler - Systems Programming
Mukesh Tekwani
 
Data communications ch 1
Mukesh Tekwani
 
Chap 3 data and signals
Mukesh Tekwani
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
 
Introduction to systems programming
Mukesh Tekwani
 
Ad

Similar to Java chapter 6 - Arrays -syntax and use (20)

PDF
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
 
PDF
javaarray
Arjun Shanka
 
PPTX
Arrays in programming
TaseerRao
 
PPT
L10 array
teach4uin
 
PDF
Learn Java Part 8
Gurpreet singh
 
PDF
Arrays Java
Jose Sumba
 
PDF
Week06
hccit
 
PPTX
OOPs with java
AAKANKSHA JAIN
 
PPT
Comp102 lec 8
Fraz Bakhsh
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
PPTX
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
ch06.ppt
ansariparveen06
 
PPT
array Details
shivas379526
 
PPT
ch06.ppt
chandrasekar529044
 
PPT
Data Structure Midterm Lesson Arrays
Maulen Bale
 
PPTX
6_Array.pptx
shafat6712
 
PDF
Arrays in Java
Naz Abdalla
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
17-Arrays en java presentación documento
DiegoGamboaSafla
 
javaarray
Arjun Shanka
 
Arrays in programming
TaseerRao
 
L10 array
teach4uin
 
Learn Java Part 8
Gurpreet singh
 
Arrays Java
Jose Sumba
 
Week06
hccit
 
OOPs with java
AAKANKSHA JAIN
 
Comp102 lec 8
Fraz Bakhsh
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
Upstate CSCI 200 Java Chapter 8 - Arrays
DanWooster1
 
ch06.ppt
AqeelAbbas94
 
ch06.ppt
ansariparveen06
 
array Details
shivas379526
 
Data Structure Midterm Lesson Arrays
Maulen Bale
 
6_Array.pptx
shafat6712
 
Arrays in Java
Naz Abdalla
 
Ad

More from Mukesh Tekwani (20)

PDF
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
PPSX
Circular motion
Mukesh Tekwani
 
PPSX
Gravitation
Mukesh Tekwani
 
PDF
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
PPTX
Hexadecimal to binary conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to decimal conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to octal conversion
Mukesh Tekwani
 
PPTX
Gray code to binary conversion
Mukesh Tekwani
 
PPTX
What is Gray Code?
Mukesh Tekwani
 
PPSX
Decimal to Binary conversion
Mukesh Tekwani
 
PDF
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
PDF
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
PDF
Refraction of light at a plane surface
Mukesh Tekwani
 
PDF
Spherical mirrors
Mukesh Tekwani
 
PDF
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
PDF
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
PDF
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
PPSX
Cyber Laws
Mukesh Tekwani
 
PPSX
Social media
Mukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
Circular motion
Mukesh Tekwani
 
Gravitation
Mukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
Hexadecimal to binary conversion
Mukesh Tekwani
 
Hexadecimal to decimal conversion
Mukesh Tekwani
 
Hexadecimal to octal conversion
Mukesh Tekwani
 
Gray code to binary conversion
Mukesh Tekwani
 
What is Gray Code?
Mukesh Tekwani
 
Decimal to Binary conversion
Mukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
Refraction of light at a plane surface
Mukesh Tekwani
 
Spherical mirrors
Mukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
Cyber Laws
Mukesh Tekwani
 
Social media
Mukesh Tekwani
 

Recently uploaded (20)

PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Introduction presentation of the patentbutler tool
MIPLM
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
epi editorial commitee meeting presentation
MIPLM
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 

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 [[email protected]] 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