Program Elements -- Introduction • Chapter 3 focuses on:

advertisement
Java Software Solutions
Lewis and Loftus
Program Elements -- Introduction
• We can now examine the core elements of programming
• Chapter 3 focuses on:
–
–
–
–
–
Chapter 3
data types
variable declaration and use
operators and expressions
decisions and loops
input and output
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
1
Java Software Solutions
Lewis and Loftus
Primitive Data Types
• A data type is defined by a set of values and the
operators you can perform on them
• Each value stored in memory is associated with a
particular data type
• The Java language has several predefined types, called
primitive data types
• The following reserved words represent eight different
primitive types:
– byte, short, int, long, float, double, boolean, char
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
2
Java Software Solutions
Lewis and Loftus
Variables
• A variable is an identifier that represents a location in
memory that holds a particular type of data
• Variables must be declared before they can be used
• The syntax of a variable declaration is:
data-type variable-name;
• For example:
int total;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
9
Java Software Solutions
Lewis and Loftus
Variables
• Multiple variables can be declared on the same line:
int total, count, sum;
• Variables can be initialized (given an initial value) in the
declaration:
int total = 0, count = 20;
float unit_price = 57.25;
• See Piano_Keys.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
10
Java Software Solutions
Lewis and Loftus
Assignment Statements
• An assignment statement takes the following form:
variable-name = expression;
• The expression is evaluated and the result is stored in the
variable, overwriting the value currently stored in the
variable
• See United_States.java
• The expression can be a single value or a more
complicated calculation
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
11
Java Software Solutions
Lewis and Loftus
Constants
• A constant is similar to a variable except that they keep
the same value throughout their existence
• They are specified using the reserved word final in
the declaration
• For example:
final double PI = 3.14159;
final int STUDENTS = 25;
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
12
Java Software Solutions
Lewis and Loftus
Constants
• When appropriate, constants are better than variables
because:
– they prevent inadvertent errors because their value cannot
change
• They are better than literal values because:
– they make code more readable by giving meaning to a value
– they facilitate change because the value is only specified in one
place
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
13
Java Software Solutions
Lewis and Loftus
Input and Output
• Java I/O is based on input streams and output streams
• There are three predefined standard streams:
Stream
Purpose
Default Device
System.in
System.out
System.err
reading input
writing output
writing errors
keyboard
monitor
monitor
• The print and println methods write to standard
output
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
14
Java Software Solutions
Lewis and Loftus
Escape Sequences
• See Echo.java
• An escape sequence is a special sequence of characters
preceded by a backslash (\)
• They indicate some special purpose, such as:
Chapter 3
Escape Sequence
Meaning
\t
\n
\"
\'
\\
tab
new line
double quote
single quote
backslash
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
16
Java Software Solutions
Lewis and Loftus
Numeric Input
• Converting a string that holds an integer into the integer
value can be done with a method in the Integer
wrapper class:
value = Integer.parseInt (my_string);
• A value can be read and converted in one line:
num = Integer.parseInt (stdin.readLine());
• See Addition.java and Addition2.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
18
Java Software Solutions
Lewis and Loftus
Program Development
• The creation of software involves four basic activities:
–
–
–
–
establishing the requirements
creating a design
implementing the code
testing the implementation
• The development process is much more involved that
this, but these basic steps are a good starting point
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
36
Java Software Solutions
Lewis and Loftus
Requirements
• Requirements specify the tasks a program must
accomplish (what to do, not how to do it)
• They often address the user interface
• An initial set of requirements are often provided, but
usually must be critiqued, modified, and expanded
• It is often difficult to establish detailed, unambiguous,
complete requirements
• Careful attention to the requirements can save significant
time and money in the overall project
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
37
Java Software Solutions
Lewis and Loftus
Design
• A program follows an algorithm, which is a step-by-step
process for solving a problem
• The design specifies the algorithms and data needed
• In object-oriented development, it establishes the classes,
objects, and methods that are required
• The details of a method may be expressed in pseudocode,
which is code-like, but does not necessarily follow any
specific syntax
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
38
Java Software Solutions
Lewis and Loftus
Implementation
• Implementation is the process of translating a design into
source code
• Most novice programmers think that writing code is the
heart of software development, but it actually should be
the least creative
• Almost all important decisions are made during
requirements analysis and design
• Implementation should focus on coding details, including
style guidelines and documentation
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
39
Java Software Solutions
Lewis and Loftus
Testing
• A program should be executed multiple times with
various input in an attempt to find errors
• Debugging is the process of discovering the cause of a
problem and fixing it
• Programmers often erroneously think that there is "only
one more bug" to fix
• Tests should focus on design details as well as overall
requirements
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
40
Java Software Solutions
Lewis and Loftus
Program Development
• See Average.java
• Follow the process of requirements analysis, design,
implementation, and testing
• There are always multiple ways to design and implement
a program
• Any design has advantages and disadvantages; there are
always trade-offs
• See Average2.java
Chapter 3
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
41
Java Software Solutions
Lewis and Loftus
Objects and Classes -- Introduction
• Now that some low-level programming concepts have
been established, we can examine objects in more detail
• Chapter 4 focuses on:
–
–
–
–
–
–
–
–
Chapter 4
the concept of objects
the use of classes to create objects
using predefined classes
defining methods and passing parameters
defining classes
visibility modifiers
static variables and methods
method overloading
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
1
Java Software Solutions
Lewis and Loftus
Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or be done to it)
• For example, a particular bank account
–
–
–
–
Chapter 4
has an account number
has a current balance
can be deposited into
can be withdrawn from
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
2
Java Software Solutions
Lewis and Loftus
Classes
• A class is a blueprint of an object
• It is the model or pattern from which objects are created
• A class defines the methods and types of data associated
with an object
• Creating an object from a class is called instantiation; an
object is an instance of a particular class
• For example, the Account class could describe many
bank accounts, but toms_savings is a particular
bank account with a particular balance
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
3
Java Software Solutions
Lewis and Loftus
Creating Objects
• The new operator creates an object from a class:
Account toms_savings = new Account ();
• This declaration asserts that toms_savings is a
variable that refers to an object created from the
Account class
• It is initialized to the object created by the new
operator
• The newly created object is set up by a call to a
constructor of the class
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
4
Java Software Solutions
Lewis and Loftus
Constructors
• A constructor is a special method used to set up an object
• It has the same name as the class
• It can take parameters, which are often used to initialize
some variables in the object
• For example, the Account constructor could be set up
to take a parameter specifying its initial balance:
Account toms_savings = new Account (125.89);
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
5
Java Software Solutions
Lewis and Loftus
Object References
• The declaration of the object reference variable and the
creation of the object can be separate activities:
Account toms_savings;
toms_savings = new Account (125.89);
• Once an object exists, its methods can be invoked using
the dot operator:
toms_savings.deposit (35.00);
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
6
Java Software Solutions
Lewis and Loftus
The String Class
• A character string in Java is an object, defined by the
String class
String name = new String ("Ken Arnold");
• Because strings are so common, Java allows an
abbreviated syntax:
String name = "Ken Arnold";
• Java strings are immutable; once a string object has a
value, it cannot be changed
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
7
Java Software Solutions
Lewis and Loftus
The String Class
• A character in a string can be referred to by its position,
or index
• The index of the first character is zero
• The String class is defined in the java.lang
package (and is therefore automatically imported)
• Many helpful methods are defined in the String class
• See Carpe_Diem.java
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
8
Java Software Solutions
Lewis and Loftus
The StringTokenizer Class
• The StringTokenizer class makes it easy to break
up a string into pieces called tokens
• By default, the delimiters for the tokens are the space,
tab, carriage return, and newline characters (white space)
• The StringTokenizer class is defined in the
java.util package
• See Int_Reader.java
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
9
Java Software Solutions
Lewis and Loftus
The Random Class
• A program may need to produce a random number
• The Random class provides methods to simulate a
random number generator
• The nextInt method returns a random number from
the entire spectrum of int values
• Usually, the number must be scaled and shifted into a
particular range to be useful
• See Flip.java
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
10
Java Software Solutions
Lewis and Loftus
Garbage Collection
• When an object no longer has any valid references to it,
it can no longer be accessed by the program
• It is useless, and therefore called garbage
• Java performs automatic garbage collection periodically,
returning an object's memory to the system for future use
• In other languages, the programmer has the responsibility
for performing garbage collection
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
16
Java Software Solutions
Lewis and Loftus
Methods
• A class contains methods; prior to defining our own
classes, we must explore method definitions
• We've defined the main method many times
• All methods follow the same syntax:
return-type method-name ( parameter-list ) {
statement-list
}
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
17
Java Software Solutions
Lewis and Loftus
Methods
• A method definition:
int third_power (int number) {
int cube;
cube = number * number * number;
return cube;
}
Chapter 4
// method third_power
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
18
Java Software Solutions
Lewis and Loftus
Methods
• A method may contain local declarations as well as
executable statements
• Variables declared locally can only be used locally
• The third_power method could be written without
any local variables:
int third_power (int number) {
return number * number * number;
}
Chapter 4
// method third_power
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
19
Java Software Solutions
Lewis and Loftus
The return Statement
• The return type of a method indicates the type of value
that the method sends back to the calling location
• A method that does not return a value (such as main)
has a void return type
• The return statement specifies the value that will be
returned
• Its expression must conform to the return type
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
20
Java Software Solutions
Lewis and Loftus
Method Flow of Control
• The main method is invoked by the system when you
submit the bytecode to the interpreter
• Each method call returns to the place that called it
main
method1
method2
method2();
method1();
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
21
Java Software Solutions
Lewis and Loftus
Defining Classes
• The syntax for defining a class is:
class class-name {
declarations
constructors
methods
}
• The variables, constructors, and methods of a class are
generically called members of the class
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
24
Java Software Solutions
Lewis and Loftus
Defining Classes
class Account {
int account_number;
double balance;
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
void deposit (double amount) {
balance = balance + amount;
} // method deposit
}
Chapter 4
// class Account
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
25
Java Software Solutions
Lewis and Loftus
Constructors
• A constructor:
–
–
–
–
–
is a special method that is used to set up a newly created object
often sets the initial values of variables
has the same name as the class
does not return a value
has no return type, not even void
• The programmer does not have to define a constructor
for a class
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
26
Java Software Solutions
Lewis and Loftus
Classes and Objects
• A class defines the data types for an object, but a class
does not store data values
• Each object has its own unique data space
• The variables defined in a class are called instance
variables because each instance of the class has its own
• All methods in a class have access to all instance
variables of the class
• Methods are shared among all objects of a class
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
27
Java Software Solutions
Lewis and Loftus
Classes and Objects
Objects
account_number
2908371
Class
balance
573.21
int account_number
double balance
account_number
4113787
balance
9211.84
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
28
Java Software Solutions
Lewis and Loftus
Encapsulation
• You can take one of two views of an object:
– internal - the structure of its data, the algorithms used by its
methods
– external - the interaction of the object with other objects in the
program
• From the external view, an object is an encapsulated
entity, providing a set of specific services
• These services define the interface to the object
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
29
Java Software Solutions
Lewis and Loftus
Encapsulation
• An object should be self-governing; any changes to the
object's state (its variables) should be accomplished by
that object's methods
• We should make it difficult, if not impossible, for another
object to "reach in" and alter an object's state
• The user, or client, of an object can request its services,
but it should not have to be aware of how those services
are accomplished
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
30
Java Software Solutions
Lewis and Loftus
Encapsulation
• An encapsulated object can be thought of as a black box;
its inner workings are hidden to the client
toms_savings
deposit
withdraw
add_interest
client
produce_statement
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
31
Java Software Solutions
Lewis and Loftus
Abstraction
• Encapsulation is a powerful abstraction
• An abstraction hides the right details at the right time
• We use abstractions every day:
– driving a car
– using a computer
• Encapsulation makes an object easy to manage mentally
because its interaction with clients is limited to a set of
well-defined services
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
32
Java Software Solutions
Lewis and Loftus
Visibility Modifiers
• We accomplish encapsulation through the appropriate
use of visibility modifiers
• A modifier is a Java reserved word that specifies
particular characteristics of a programming construct
• We've used the modifier final to define a constant
• Java has three visibility modifiers: public, private,
and protected
• We will discuss the protected modifier later
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
33
Java Software Solutions
Lewis and Loftus
Visibility Modifiers
• Members of a class that are declared with public
visibility can be accessed from anywhere
• Members of a class that are declared with private
visibility can only be accessed from inside the class
• Members declared without a visibility modifier have
default visibility and can be accessed by any class in the
same package
• Java modifiers are discussed in detail in Appendix F
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
34
Java Software Solutions
Lewis and Loftus
Visibility Modifiers
• As a general rule, no object's data should be declared
with public visibility
• Methods that provide the object's services are usually
declared with public visibility so that they can be
invoked by clients
• Public methods are also called service methods
• Other methods, called support methods, can be defined
that assist the service methods; they should not be
declared with public visibility
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
35
Java Software Solutions
Lewis and Loftus
Classes and Objects
• See Tunes.java
music
add_cds
main
print
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
36
Java Software Solutions
Lewis and Loftus
The static Modifier
• The static modifier can be applied to variables or
methods
• It associates a variable or method with the class rather
than an object
• This approach is a distinct departure from the normal
way of thinking about objects
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
37
Java Software Solutions
Lewis and Loftus
Static Variables
• Normally, each object has its own data space
• If a variable is declared as static, only one copy of the
variable exists for all objects of the class
private static int count;
• Changing the value of a static variable in one object
changes it for all others
• Static variables are sometimes called class variables
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
38
Java Software Solutions
Lewis and Loftus
Static Methods
• Normally, we invoke a method through an instance (an
object) of a class
• If a method is declared as static, it can be invoked
through the class name; no object needs to exist
• For example, the Math class in the java.lang
package contains several static mathematical operations
Math.abs (num) -- absolute value
Math.sqrt (num) -- square root
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
39
Java Software Solutions
Lewis and Loftus
Static Methods
• The main method is static; it is invoked by the system
without creating an object
• Static methods cannot reference instance variables,
because instance variables don't exist until an object
exists
• However, they can reference static variables or local
variables
• Static methods are sometimes called class methods
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
40
Java Software Solutions
Lewis and Loftus
Overloaded Methods
• Method overloading is the process of using the same
method name for multiple methods
• The signature of each overloaded method must be unique
• The signature is based on the number, type, and order of
the parameters
• The compiler must be able to determine which version of
the method is being invoked by analyzing the parameters
• The return type of the method is not part of the signature
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
41
Java Software Solutions
Lewis and Loftus
Overloaded Methods
• The println method is overloaded:
println (String s)
println (int i)
println (double d)
etc.
• The lines
System.out.println ("The total is:");
System.out.println (total);
invoke different versions of the println method
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
42
Java Software Solutions
Lewis and Loftus
Overloaded Methods
• Constructors are often overloaded to provide multiple
ways to set up a new object
Account (int account) {
account_number = account;
balance = 0.0;
}
// constructor Account
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
• See Casino.java
Chapter 4
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
43
Java Software Solutions
Lewis and Loftus
Classes and Objects
• See Storm.java
Chapter 4
current_size
4
Storm
current_size
18
current_size
12
drop1
drop2
drop3
current_size
7
drop4
drop5
current_size
24
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
45
Java Software Solutions
Lewis and Loftus
Objects for Organizing Data -- Introduction
• As our programs get more sophisticated, we need
assistance organizing large amounts of data
• Chapter 6 focuses on:
–
–
–
–
–
array declaration and use
arrays of objects
parameters and arrays
multidimensional arrays
the Vector class
– additional techniques for managing strings
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
1
Java Software Solutions
Lewis and Loftus
Arrays
• An array is an ordered list of values
• Each value has a numeric index
• An array of size N is indexed from zero to N-1
• The following array of integers has a size of 10 and is
indexed from 0 to 9
0
scores
Chapter 6
1
2
3
4
5
6
7
8
9
79 87 94 82 67 98 87 81 74 91
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
2
Java Software Solutions
Lewis and Loftus
Arrays
• A particular value in an array is referenced using the
array name followed by the index in brackets
• For example, the expression
scores[4]
refers to the value 67 (which is the 5th value in the array)
• That expression represents a place to store a single
integer, can can be used wherever an integer variable can
• For example, it can be assigned a value, printed, used in
a calculation
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
3
Java Software Solutions
Lewis and Loftus
Arrays
• An array stores multiple values of the same type
• That type can be primitive types or objects
• Therefore, we can create an array of integers, or an array
of characters, or an array of String objects, etc.
• In Java, the array itself is an object
• Therefore the name of the array is a object reference
variable, and the array itself is instantiated separately
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
4
Java Software Solutions
Lewis and Loftus
Declaring Arrays
• The scores array could be declared as follows:
int[] scores = new int[10];
• Note that the type of the array does not specify its size,
but each object of that type has a specific size
• The type of the variable scores is int[] (an array of
integers)
• It is set to a newly instantiated array of 10 integers
• See Basic_Array.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
5
Java Software Solutions
Lewis and Loftus
Declaring Arrays
• Some examples of array declarations:
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
6
Java Software Solutions
Lewis and Loftus
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid
element
• That is, they must be in bounds (0 to N-1)
• The Java interpreter will throw an exception if an array
index is out of bounds
• This is called automatic bounds checking
• Its common to inadvertently introduce off-by-one errors
when using arrays
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
7
Java Software Solutions
Lewis and Loftus
Bounds Checking
• Each array object has a public constant called length
that stores the size of the array
• It is referenced through the array name (just like any
other object):
scores.length
• Note that length holds the number of elements, not the
largest index
• See Reverse_Numbers.java and
Adjust_Test_Scores.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
8
Java Software Solutions
Lewis and Loftus
Array Declarations Revisited
• The brackets of the array type can be associated with the
element type or with the name of the array
• Therefore
float[] prices;
and
float prices[];
are essentially equivalent
• The first format is usually more readable
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
9
Java Software Solutions
Lewis and Loftus
Initializer Lists
• An initializer list can be used to instantiate and initialize
an array in one step
• The values are delimited by braces and separated by
commas
• Examples:
int[] units = {147, 323, 89, 933, 540,
269, 97, 114, 298, 476};
char[] letter_grades = {'A', 'B', 'C',
'D', 'F'};
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
10
Java Software Solutions
Lewis and Loftus
Initializer Lists
• Note that when an initializer list is used:
– the new operator is not used
– no size value is specified
• The size of the array is determined by the number of
items in the initializer list
• An initializer list can only be used in the declaration of
an array
• See Primes.java and Sales_Analysis.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
11
Java Software Solutions
Lewis and Loftus
Arrays of Objects
• The elements of an array can be object references
• The declaration
String[] words = new String[25];
reserves space to store 25 references to String objects
• It does NOT create the String objects themselves
• Each object stored in an array must be instantiated
separately
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
12
Java Software Solutions
Lewis and Loftus
Arrays of Objects
• See Children.java and Presidents.java
• Objects can have arrays as instance variables
• Therefore, fairly complex structures can be created
simply with arrays and objects
• The software designer must carefully determine an
organization of data and objects that makes sense for the
situation
• See Roll_Call.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
13
Java Software Solutions
Lewis and Loftus
Arrays as Parameters
• An entire array can be passed to a method as a parameter
• Like any other object, the reference to the array is
passed, making the formal and actual parameters aliases
of each other
• Changing an array element in the method changes the
original
• An array element can be passed to a method as well, and
follow the parameter passing rules of that element's type
• See Array_Test.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
14
Java Software Solutions
Lewis and Loftus
Multidimensional Arrays
• A one-dimensional array stores a simple list of values
• A two-dimensional array can be thought of as a table of
values, with rows and columns
• A two-dimensional array element is referenced using two
index values
• To be precise, a two-dimensional array in Java is an array
of arrays, therefore each row can have a different length
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
15
Java Software Solutions
Lewis and Loftus
Multidimensional Arrays
• An initializer list can be used to create and set up a
multidimensional array
• Each element in the list is itself an initializer list
• Note that each array dimension has its own length
constant
• See Multi_Array_Test.java and
Soda_Survey.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
16
Java Software Solutions
Lewis and Loftus
The Vector Class
• An object of class Vector is similar to an array in that
it stores multiple values
• However, a vector
– only stores objects
– does not have the indexing syntax that arrays have
• Service methods are used to interact with a vector
• The Vector class is part of the java.util package
• See Beatles.java and ZZ_Top.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
17
Java Software Solutions
Lewis and Loftus
The Vector Class
• An important difference between an array and a vector is
that a vector can be thought of as a dynamic, able to
change its size as needed
• Each vector initially has a certain amount of memory
space reserved for storing elements
• If an element is added that doesn't fit in the existing
space, more room is automatically acquired
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
18
Java Software Solutions
Lewis and Loftus
The Vector Class
• A vector is implemented using an array
• Whenever new space is required, a new, larger array is
created, and the values are copied from the original to the
new array
• To insert an element, existing elements are first copied,
one by one, to another position in the array
• Therefore, the implementation of Vector in the API is
not very efficient
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
19
Java Software Solutions
Lewis and Loftus
The StringTokenizer Class Revisited
• We've seen a StringTokenizer object separate a
string into separate tokens
• By default, those tokens are delimited by white space
• But by using other StringTokenizer constructors,
we can define the delimiters used to define a token
• We can also set whether we want the delimiters
themselves returned as tokens
• See Voltaire.java and URL_Tokens.java
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
20
Java Software Solutions
Lewis and Loftus
The StringBuffer Class
• Recall that the value of a String object is immutable;
once set it cannot be changed
• The StringBuffer class can be used to define a
character string whose value can change
• It's service methods include the ability to append and
insert characters
• See Money.java
• However, most functionality defined by the
StringBuffer class can be accomplished with
String objects and string concatenation
Chapter 6
Copyright 1997 by John Lewis and William Loftus. All rights reserved.
21
Download