0% found this document useful (0 votes)
54 views21 pages

Arrays Part 2

The document provides an overview of arrays in Java, including that arrays allow storing multiple values of the same type using a single name, arrays are declared with a base type and size, and individual elements can be accessed using subscript notation. It describes how to declare, initialize, access, and pass array elements and names as arguments to methods in Java. The document explains some key array concepts like length, indexes, and that arrays are reference types.

Uploaded by

nm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views21 pages

Arrays Part 2

The document provides an overview of arrays in Java, including that arrays allow storing multiple values of the same type using a single name, arrays are declared with a base type and size, and individual elements can be accessed using subscript notation. It describes how to declare, initialize, access, and pass array elements and names as arguments to methods in Java. The document explains some key array concepts like length, indexes, and that arrays are reference types.

Uploaded by

nm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Overview

• An array
– a single name for a collection of data values
– all of the same data type
– subscript notation to identify one of the values
• A carryover from earlier programming languages
• More than a primitive type, less than an object
– like objects when used as method parameters and return
types
– do not have or use inheritance
• Accessing each of the values in an array
– Usually a for loop
Creating Arrays
• General syntax for declaring an array:

Base_Type[] Array_Name = new Base_Type[Length];

• Examples:
80-element array with base type char:
char[] symbol = new char[80];

100-element array of doubles:


double[] reading = new double[100];

70-element array of ints:


int[] marks = new int[70];
Three Ways to Use [ ] (Brackets)
with an Array Name
1. Declaring an array: int[] pressure
• creates a name of type "int array"
– types int and int[] are different
• int[]: type of the array
• int : type of the individual values

2. To create a new array, e.g. pressure = new int[100];

3. To refer to a specific element in the array


- also called an indexed variable, e.g.

pressure[3] = keyboard.nextInt();
System.out.println("You entered" + pressure[3]);
Some Array Terminology
Array name
temperature[n + 2]
Index - also called a subscript
- must be an int,
- or an expression that evaluates to an int
temperature[n + 2]
Indexed variable - also called an
element or subscripted variable
temperature[n + 2] Value of the indexed variable
- also called an element of the array
temperature[n + 2] = 32;
Array Length
• Specified by the number in brackets when created with new
– maximum number of elements the array can hold
– storage is allocated whether or not the elements are
assigned values

• the attribute length,


Species[] entry = new Species[20];
System.out.println(entry.length);

• The length attribute is established in the declaration and


cannot be changed unless the array is redeclared
Subscript Range
• Array subscripts use zero-numbering
– the first element has subscript 0
– the second element has subscript 1
– etc. - the nth element has subscript n-1
– the last element has subscript length-1
• For example: an int array with 4 elements
Subscript: 0 1 2 3
Value: 97 86 92 71
Subscript out of Range Error
• Using a subscript larger than length-1 causes a run time
(not a compiler) error
– an ArrayOutOfBoundsException is thrown
• you do not need to catch it
• you need to fix the problem and recompile your code
• Other programming languages, e.g. C and C++, do not even
cause a run time error!
– one of the most dangerous characteristics of these
languages is that they allow out of bounds array indices.
Array Length Specified at Run-
time
// array length specified at compile-time
int[] array1 = new int[10];

// array length specified at run-time


// calculate size…
int size = …;
int[] array2 = new int[size];
Initializing an Array's Values
in Its Declaration
• can be initialized by putting a comma-separated list in braces
• Uninitialized elements will be assigned some default value, e.g. 0 for
int arrays (explicit initialization is recommended)
• The length of an array is automatically determined when the values are
explicitly initialized in the declaration
• For example:
double[] reading = {5.1, 3.02, 9.65};
System.out.println(reading.length);

- displays 3, the length of the array reading


Initializing Array Elements in a
Loop
• A for loop is commonly used to initialize array elements
• For example:
int i;//loop counter/array index
int[] a = new int[10];
for(i = 0; i < a.length; i++)
a[i] = 0;
– note that the loop counter/array index goes from 0 to length - 1
– it counts through length = 10 iterations/elements using the zero-
numbering of the array index

Programming Tip:
Do not count on default initial values for array elements
– explicitly initialize elements in the declaration or in a loop
Arrays, Classes, and Methods
An array of a class can This excerpt from the Sales Report program
be declared and the
in the text uses the SalesAssociate class
class's methods applied
to the elements of the to create an array of sales associates:
array.
public void getFigures()
create an array of {
SalesAssociates System.out.println("Enter number of sales associates:");
numberOfAssociates = SavitchIn.readLineInt();
SalesAssociate[] record =
each array element is new SalesAssociate[numberOfAssociates];
a SalesAssociate for (int i = 0; i < numberOfAssociates; i++)
variable {
record[i] = new SalesAssociate();
System.out.println("Enter data for associate " + (i + 1));
use the readInput record[i].readInput();
method of System.out.println();
SalesAssociate }
}
Arrays and Array Elements
as Method Arguments
• Arrays and array elements can be
– used with classes and methods just like other
objects
– be an argument in a method
– returned by methods
public static void main(String[] arg)
Indexed {
Scanner keyboard = new Scanner(System.in);a
Variables System.out.println("Enter your score on exam 1:");
int firstScore = keyboard.nextInt();
as Method int[ ] nextScore = new int[3];
int i;
Arguments double possibleAverage;
for (i = 0; i < nextScore.length; i++)
nextScore[i] = 80 + 10*i;
nextScore is for (i = 0; i < nextScore.length; i++)
an array of ints {
possibleAverage = average(firstScore, nextScore[i]);
System.out.println("If your score on exam 2 is "
an element of + nextScore[i]);
nextScore is System.out.println("your average will be "
+ possibleAverage);
an argument of
}
method }
average public static double average(int n1, int n2)
{
average return (n1 + n2)/2.0;
method definition }
When Can a Method Change an
Indexed Variable Argument?
• primitive types are “call-by-value”
– only a copy of the value is passed as an argument
– method cannot change the value of the indexed variable
• class types are reference types (“call by reference”)
– pass the address of the object
– the corresponding parameter in the method definition
becomes an alias of the object
– the method has access to the actual object
– so the method can change the value of the indexed
variable if it is a class (and not a primitive) type
Passing Array Elements
int[] grade = new int[10];
obj.method(grade[i]); // grade[i] cannot be changed

… method(int grade) // pass by value; a copy


{
}
______________________________________________________
Person[] roster = new Person[10];
obj.method(roster[i]); // roster[i] can be changed

… method(Person p) // pass by reference; an alias


{
}
Array Names as Method
Arguments
• Use just the array name and no brackets
• Pass by reference
– the method has access to the original array and can change the
value of the elements
• The length of the array passed can be different for each
call
– when you define the method you do not need to know
the length of the array that will be passed
– use the length attribute inside the method to avoid
ArrayIndexOutOfBoundsExceptions
Example: An Array as an Argument
in a Method Call the method's argument
is the name of an array
of characters
public static void showArray(char[] a)
{
int i;
for(i = 0; i < a.length; i++)
System.out.println(a[i]);
}
uses the length attribute
------------- to control the loop
char[] grades = new char[45]; allows different size arrays
MyClass.showArray(grades); and avoids index-out-of-
bounds exceptions
Arguments for the Method main
• The heading for the main method shows a parameter that is an array
of Strings:
public static void main(String[] arg)
• When you run a program from the command line, all words after the
class name will be passed to the main method in the arg array.
java TestProgram Josephine Student
• The following main method in the class TestProgram will print
out the first two arguments it receives:
Public static void main(String[] arg)
{
System.out.println(“Hello “ + arg[0] + “ “ + arg[1]);
}

• In this example, the output from the command line above will be:
Hello Josephine Student
Using = with Array Names:
Remember They Are Reference Types

int[] a = new int[3];


int[] b = new int[3];
for(int i=0; i < a.length; i++) This does not create a
copy of array a;
a[i] = i;
it makes b another name
b = a; for array a.
System.out.println(a[2] + " " + b[2]);
a[2] = 10;
System.out.println(a[2] + " " + b[2]);

The output for this code will be: A value changed in a


2 2 is the same value
10 10 obtained with b
Using == with array names:
remember they are reference types
int i; a and b are both
3-element arrays of ints
int[] a = new int[3];
int[] b = new int[3];
all elements of a and b are
for(i=0; i < a.length; i++)
assigned the value 0
a[i] = 0;
for(i=0; i < b.length; i++) tests if the
b[i] = 0; addresses of a
if(b == a) and b are equal,
System.out.println("a equals b"); not if the array
else values are equal
System.out.println("a does not equal b");
The output for this code will be " a does not equal b"
because the addresses of the arrays are not equal.
Behavior of Three Operations
Primitive Class Entire Array
Type Type Array Element
Assignment Copy content Copy Copy Depends on
(=) address address primitive/
class type
Equality Compare Compare Compare Depends on
(==) content address address primitive/
class type
Parameter Pass by Pass by Pass by Depends on
Passing value reference reference primitive/
(content) (address) (address) class type

You might also like