Download eng.harran.edu.tr

Document related concepts
no text concepts found
Transcript
1
1
Introduction
to Java Applications
 2005 Pearson Education, Inc. All rights reserved.
2
2.1 Introduction
• Java application programming
– Display messages
– Obtain information from the user
– Arithmetic calculations
– Decision-making fundamentals
 2005 Pearson Education, Inc. All rights reserved.
3
2.2 First Program in Java: Printing a Line
of Text
• Application
– Executes when you use the java command to launch the
Java Virtual Machine (JVM)
• Sample program
– Displays a line of text
– Illustrates several important Java language features
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 2.1: Welcome1.java
2
// Text-printing program.
4
Outline
3
4
public class Welcome1
5
{
6
// main method begins execution of Java application
7
public static void main( String args[] )
8
{
9
Welcome1.java
System.out.println( "Welcome to Java Programming!" );
10
11
} // end method main
12
13 } // end clazss Welcome1
Welcome to Java Programming!
 2005 Pearson Education,
Inc. All rights reserved.
5
2.2 First Program in Java: Printing a Line
of Text (Cont.)
4
public class Welcome1
– Saving files
• File name must be class name with .java extension
• Welcome1.java
5
{
– Left brace {
• Begins body of every class
• Right brace ends declarations (line 13)
 2005 Pearson Education, Inc. All rights reserved.
6
Common Programming Error 2.3
It is an error for a public class to have a file
name that is not identical to the class name
(plus the .java extension) in terms of both
spelling and capitalization.
 2005 Pearson Education, Inc. All rights reserved.
7
2.2 First Program in Java: Printing a Line
of Text (Cont.)
9
System.out.println( "Welcome to Java Programming!" );
– Instructs computer to perform an action
• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
– This line known as a statement
• Statements must end with semicolon ;
 2005 Pearson Education, Inc. All rights reserved.
8
2.4 Displaying Text with printf
•System.out.printf
– New feature of J2SE 5.0
– Displays formatted data
9
10
System.out.printf( "%s\n%s\n",
"Welcome to", "Java Programming!" );
– Format string
• Fixed text
• Format specifier – placeholder for a value
– Format specifier %s – placeholder for a string
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 2.6: Welcome4.java
2
// Printing multiple lines in a dialog box.
9
Outline
3
4
public class Welcome4
5
{
Welcome4.java
6
// main method begins execution of Java application
7
public static void main( String args[] )
main
8
{
printf
9
10
System.out.printf( "%s\n%s\n",
System.out.printf
displays formatted data.
"Welcome to", "Java Programming!" );
11
12
} // end method main
13
14 } // end class Welcome4
Welcome to
Java Programming!
Program output
 2005 Pearson Education,
Inc. All rights reserved.
10
2.5 Another Java Application: Adding
Integers
• Upcoming program
– Use Scanner to read two integers from user
– Use printf to display sum of the two values
– Use packages
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 2.7: Addition.java
2
// Addition program that displays the sum of two numbers.
3
import java.util.Scanner; // program uses class Scanner
11
import declaration imports class
Scanner from package java.util.
4
5
public class Addition
6
{
Outline
7
// main method begins execution of Java application
8
public static void main( String args[] )
9
{
Addition.java
(1 of 2)
10
// create Scanner to obtain input from command window
11
Scanner input = new Scanner( System.in );
import
declaration
Declare and initialize
variable
input, which is a Scanner.
Scanner
12
13
int number1; // first number to add
14
int number2; // second number to add
15
int sum; // sum of number1 and number2
Declare variables number1,
nextInt
number2 and sum.
16
17
System.out.print( "Enter first integer: " ); // prompt
18
number1 = input.nextInt(); // read first number from user
19
Read an integer from the user
and assign it to number1.
 2005 Pearson Education,
Inc. All rights reserved.
20
System.out.print( "Enter second integer: " ); // prompt
21
number2 = input.nextInt(); // read second number from user
22
23
sum = number1 + number2; // add numbers
24
25
Outline
Read an integer from the user
and assign it to number2.
Calculate the sum of the
Addition.java
variables number1 and
number2, assign result to sum.(2 of 2)
System.out.printf( "Sum is %d\n", sum ); // display sum
26
27
12
} // end method main
28
29 } // end class Addition
Enter first integer: 45
Enter second integer: 72
Sum is 117
Display the sum using
formatted output.
4. Addition
5. printf
Two integers entered by the user.
 2005 Pearson Education,
Inc. All rights reserved.
13
2.5 Another Java Application: Adding
Integers (Cont.)
3
import java.util.Scanner;
// program uses class Scanner
– import declarations
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class Scanner from java.util
package
5
6
public class Addition
{
– Begins public class Addition
• Recall that file name must be Addition.java
– Lines 8-9: begins main
 2005 Pearson Education, Inc. All rights reserved.
14
Common Programming Error 2.8
All import declarations must appear before the
first class declaration in the file. Placing an
import declaration inside a class declaration’s
body or after a class declaration is a syntax
error.
 2005 Pearson Education, Inc. All rights reserved.
15
Error-Prevention Tip 2.7
Forgetting to include an import declaration for
a class used in your program typically results
in a compilation error containing a message
such as “cannot resolve symbol.” When this
occurs, check that you provided the proper
import declarations and that the names in the
import declarations are spelled correctly,
including proper use of uppercase and
lowercase letters.
 2005 Pearson Education, Inc. All rights reserved.
16
2.5 Another Java Application: Adding
Integers (Cont.)
10
11
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
– Variable Declaration Statement
– Variables
• Location in memory that stores a value
– Declare with name and type before use
• Input is of type Scanner
– Enables a program to read data for use
• Variable name: any valid identifier
– Declarations end with semicolons ;
– Initialize variable in its declaration
• Equal sign
• Standard input object
– System.in
 2005 Pearson Education, Inc. All rights reserved.
17
2.5 Another Java Application: Adding
Integers (Cont.)
17
System.out.print( "Enter first integer: " ); // prompt
– Message called a prompt - directs user to perform an
action
– Package java.lang
18
number1 = input.nextInt(); // read first number from user
– Result of call to nextInt given to number1 using
assignment operator =
• Assignment statement
• = binary operator - takes two operands
– Expression on right evaluated and assigned to variable
on left
• Read as: number1 gets the value of input.nextInt()
 2005 Pearson Education, Inc. All rights reserved.
18
2.5 Another Java Application: Adding
Integers (Cont.)
25
System.out.printf( "Sum is %d\n: " , sum ); // display sum
– Use System.out.printf to display results
– Format specifier %d
• Placeholder for an int value
System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );
– Calculations can also be performed inside printf
– Parentheses around the expression number1 + number2
are not required
 2005 Pearson Education, Inc. All rights reserved.
19
3.1 Introduction
• Primitive Types
• Classes
• Floating-Point numbers
 2005 Pearson Education, Inc. All rights reserved.
20
Primitive Types vs. Reference Types
• Types in Java
– Primitive
• boolean, byte, char, short, int, long, float,
double
– Reference (sometimes called nonprimitive types)
• Objects
• Default value of null
• Used to invoke an object’s methods
 2005 Pearson Education, Inc. All rights reserved.
21
3.2 Classes, Objects, Methods and
Instance Variables
• Class provides one or more methods
• Method represents task in a program
– Describes the mechanisms that actually perform its
tasks
– Hides from its user the complex tasks that it
performs
– Method call tells method to perform its task
 2005 Pearson Education, Inc. All rights reserved.
22
3.2 Classes, Objects, Methods and
Instance Variables (Cont.)
• Classes contain one or more attributes
– Specified by instance variables
– Carried with the object as it is used
 2005 Pearson Education, Inc. All rights reserved.
23
Common Programming Error 3.1
•Declaring more than one public class
in the same file is a compilation error.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.1: GradeBook.java
2
// Class declaration with one method.
Outline
24
3
4
public class GradeBook
5
{
6
// display a welcome message to the GradeBook user
7
public void displayMessage()
8
{
9
10
Print line of text to output
•GradeBoo
k.java
System.out.println( "Welcome to the Grade Book!" );
} // end method displayMessage
11
12 } // end class GradeBook
 2005 Pearson Education, Inc. All rights reserved.
25
Class GradeBookTest
• Java is extensible
– Programmers can create new classes
• Class instance creation expression
– Keyword new
– Then name of class to create and parentheses
• Calling a method
– Object name, then dot separator (.)
– Then method name and parentheses
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.2: GradeBookTest.java
2
// Create a GradeBook object and call its displayMessage method.
Outline
26
3
4
public class GradeBookTest
5
{
6
// main method begins program execution
7
public static void main( String args[] )
8
{
•GradeBoo
kTest.java
Use class instance creation
9
// create a GradeBook object and assign it to myGradeBook
10
GradeBook myGradeBook = new GradeBook();
expression to create object of class
GradeBook
11
12
// call myGradeBook's displayMessage method
13
myGradeBook.displayMessage();
14
Call method displayMessage
using GradeBook object
} // end main
15
16 } // end class GradeBookTest
Welcome to the Grade Book!
 2005 Pearson Education, Inc. All rights reserved.
27
3.4 Declaring a Method with a Parameter
•Scanner methods
– nextLine reads next line of input
– next reads next word of input
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.4: GradeBook.java
2
// Class declaration with a method that has a parameter.
Outline
28
3
4
public class GradeBook
5
{
6
// display a welcome message to the GradeBook user
7
public void displayMessage( String courseName )
8
{
9
10
11
•GradeBoo
k.java
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName );
} // end method displayMessage
12
Call printf method with
courseName argument
13 } // end class GradeBook
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 3.5: GradeBookTest.java
// Create GradeBook object and pass a String to
// its displayMessage method.
import java.util.Scanner; // program uses Scanner
Outline
public class GradeBookTest
{
// main method begins program execution
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
•GradeBoo
kTest.java
// create a GradeBook object and assign it toCall
myGradeBook
nextLine method
GradeBook myGradeBook = new GradeBook();
line of input
29
to read a
// prompt for and input course name
System.out.println( "Please enter the course name:" );
String nameOfCourse = input.nextLine(); // read
line of text
Calla displayMessage
System.out.println(); // outputs a blank line
with an
argument
// call myGradeBook's displayMessage method
// and pass nameOfCourse as an argument
myGradeBook.displayMessage( nameOfCourse );
} // end main
} // end class GradeBookTest
Please enter the course name:
CS101 Introduction to Java Programming
Welcome to the grade book for
CS101 Introduction to Java Programming!
 2005 Pearson Education, Inc. All rights reserved.
30
3.5 Instance Variables, set Methods and
get Methods
• Variables declared in the body of method
– Called local variables
– Can only be used within that method
• Variables declared in a class declaration
– Called fields or instance variables
– Each object of the class has a separate instance of
the variable
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.7: GradeBook.java
2
// GradeBook class that contains a courseName instance variable
3
// and methods to set and get its value.
4
5
public class GradeBook
6
7
8
{
Outline
31
Instance variable courseName
•GradeBoo
k.java
set method for courseName
private String courseName; // course name for this GradeBook
9
10
// method to set the course name
public void setCourseName( String name )
11
12
{
13
14
} // end method setCourseName
15
// method to retrieve the course name
16
17
public String getCourseName()
{
18
19
20
return courseName;
} // end method getCourseName
21
22
23
24
25
// display a welcome message to the GradeBook user
public void displayMessage()
{
// this statement calls getCourseName to get the
// name of the course this GradeBook represents
courseName = name; // store the course name
get method for courseName
26
System.out.printf( "Welcome to the grade book for\n%s!\n",
27
getCourseName() );
Call get
28
} // end method displayMessage
29
30 } // end class GradeBook
method
 2005 Pearson Education, Inc. All rights reserved.
32
Access Modifiers public and private
• private keyword
– Used for most instance variables
– private variables and methods are accessible only
to methods of the class in which they are declared
– Declaring instance variables private is known as
data hiding
• Return type
– Indicates item returned by method
– Declared in method header
 2005 Pearson Education, Inc. All rights reserved.
33
set and get methods
•private instance variables
– Cannot be accessed directly by clients of the object
– Use set methods to alter the value
– Use get methods to retrieve the value
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.8: GradeBookTest.java
2
// Create and manipulate a GradeBook object.
3
import java.util.Scanner; // program uses Scanner
Outline
34
4
5
public class GradeBookTest
6
{
7
// main method begins program execution
8
public static void main( String args[] )
9
{
10
// create Scanner to obtain input from command window
11
Scanner input = new Scanner( System.in );
•GradeBoo
kTest.java
•(1 of 2)
12
13
// create a GradeBook object and assign it to myGradeBook
14
GradeBook myGradeBook = new GradeBook();
15
16
// display initial value of courseName
17
System.out.printf( "Initial course name is: %s\n\n",
18
19
myGradeBook.getCourseName() );
Call get method for courseName
 2005 Pearson Education, Inc. All rights reserved.
20
// prompt for and read course name
21
System.out.println( "Please enter the course name:" );
22
String theName = input.nextLine(); // read a line of text
23
myGradeBook.setCourseName( theName ); // set the course name
24
System.out.println(); // outputs a blank line
Call set method for courseName
25
26
// display welcome message after specifying course name
27
myGradeBook.displayMessage();
28
Outline
35
} // end main
29
Call displayMessage
•GradeBoo
kTest.java
•(2 of 2)
30 } // end class GradeBookTest
Initial course name is: null
Please enter the course name:
CS101 Introduction to Java Programming
Welcome to the grade book for
CS101 Introduction to Java Programming!
 2005 Pearson Education, Inc. All rights reserved.
36
3.7 Initializing Objects with Constructors
• Constructors
– Initialize an object of a class
– Java requires a constructor for every class
– Java will provide a default no-argument constructor
if none is provided
– Called when keyword new is followed by the class
name and parentheses
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.10: GradeBook.java
2
// GradeBook class with a constructor to initialize the course name.
3
4
public class GradeBook
5
{
6
private String courseName; // course name for this GradeBook
7
8
// constructor initializes courseName with String supplied as argument
9
public GradeBook( String name )
10
{
courseName = name; // initializes courseName
11
12
Constructor to initialize
courseName variable
Outline
37
•GradeBoo
k.java
•(1 of 2)
} // end constructor
13
14
// method to set the course name
15
public void setCourseName( String name )
16
{
courseName = name; // store the course name
17
18
} // end method setCourseName
19
20
// method to retrieve the course name
21
public String getCourseName()
22
{
23
24
return courseName;
} // end method getCourseName
 2005 Pearson Education, Inc. All rights reserved.
25
26
// display a welcome message to the GradeBook user
27
public void displayMessage()
28
{
Outline
29
// this statement calls getCourseName to get the
30
// name of the course this GradeBook represents
31
System.out.printf( "Welcome to the grade book for\n%s!\n",
32
getCourseName() );
33
} // end method displayMessage
38
•GradeBoo
k.java
•(2 of 2)
34
35 } // end class GradeBook
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 3.11: GradeBookTest.java
2
// GradeBook constructor used to specify the course name at the
3
// time each GradeBook object is created.
Outline
39
4
5
public class GradeBookTest
6
{
7
// main method begins program execution
8
public static void main( String args[] )
9
{
10
// create GradeBook object
11
GradeBook gradeBook1 = new GradeBook(
12
•GradeBoo
Call constructor to create first grade
kTest.java
book object
"CS101 Introduction to Java Programming" );
13
GradeBook gradeBook2 = new GradeBook(
14
"CS102 Data Structures in Java" );
Create second grade book object
15
16
// display initial value of courseName for each GradeBook
17
System.out.printf( "gradeBook1 course name is: %s\n",
18
19
20
21
gradeBook1.getCourseName() );
System.out.printf( "gradeBook2 course name is: %s\n",
gradeBook2.getCourseName() );
} // end main
22
23 } // end class GradeBookTest
gradeBook1 course name is: CS101 Introduction to Java Programming
gradeBook2 course name is: CS102 Data Structures in Java
 2005 Pearson Education, Inc. All rights reserved.
40
3.8 Floating-Point Numbers and Type
double
• Floating-point numbers
– float
– double
• Stores numbers with greater magnitude and precision
than float
 2005 Pearson Education, Inc. All rights reserved.
41
Floating-Point Number Precision and
Memory Requirements
• float
– Single-precision floating-point numbers
– Seven significant digits
• double
– Double-precision floating-point numbers
– Fifteen significant digits
 2005 Pearson Education, Inc. All rights reserved.
42
Control Statements
• If else
• Switch
• Goto
• For
• While
• Do While
 2005 Pearson Education, Inc. All rights reserved.
43
Methods: A Deeper Look
• Divide and conquer technique
– Construct a large program from smaller pieces (or
modules)
– Can be accomplished using methods
•static methods can be called without the need
for an object of the class
• Random number generation
• Constants
 2005 Pearson Education, Inc. All rights reserved.
44
6.2 Program Modules in Java
• Java Application Programming Interface (API)
– Also known as the Java Class Library
– Contains predefined methods and classes
• Related classes are organized into packages
• Includes methods for mathematics, string/character
manipulations, input/output, databases, networking, file
processing, error checking and more
 2005 Pearson Education, Inc. All rights reserved.
45
Good Programming Practice 6.1
•Familiarize yourself with the rich collection
of classes and methods provided by the Java
API
(java.sun.com/j2se/5.0/docs/api/
index.html). In Section 6.8, we present an
overview of several common packages. In
Appendix G, we explain how to navigate the
Java API documentation.
 2005 Pearson Education, Inc. All rights reserved.
46
Software Engineering Observation 6.1
•Don’t try to reinvent the wheel. When possible,
reuse Java API classes and methods. This reduces
program development time and avoids introducing
programming errors.
 2005 Pearson Education, Inc. All rights reserved.
47
6.2 Program Modules in Java (Cont.)
• Methods
– Called functions or procedures in other languages
– Modularize programs by separating its tasks into selfcontained units
– Enable a divide-and-conquer approach
– Are reusable in later programs
– Prevent repeating code
 2005 Pearson Education, Inc. All rights reserved.
48
Software Engineering Observation 6.2
•To promote software reusability, every method
should be limited to performing a single, welldefined task, and the name of the method
should express that task effectively. Such
methods make programs easier to write, debug,
maintain and modify.
 2005 Pearson Education, Inc. All rights reserved.
49
Error-Prevention Tip 6.1
•A small method that performs one task is
easier to test and debug than a larger method
that performs many tasks.
 2005 Pearson Education, Inc. All rights reserved.
50
Software Engineering Observation 6.3
•If you cannot choose a concise name that
expresses a method’s task, your method might
be attempting to perform too many diverse
tasks. It is usually best to break such a method
into several smaller method declarations.
 2005 Pearson Education, Inc. All rights reserved.
6.3 static Methods, static Fields and
Class Math
51
•static method (or class method)
– Applies to the class as a whole instead of a specific object of
the class
– Call a static method by using the method call:
ClassName.methodName( arguments )
– All methods of the Math class are static
• example: Math.sqrt( 900.0 )
 2005 Pearson Education, Inc. All rights reserved.
6.3 static Methods, static Fields and
Class Math (Cont.)
52
• Constants
– Keyword final
– Cannot be changed after initialization
•static fields (or class variables)
– Are fields where one copy of the variable is shared among
all objects of the class
•Math.PI and Math.E are final static fields
of the Math class
 2005 Pearson Education, Inc. All rights reserved.
53
Method
Description
Example
abs( x )
absolute value of x
ceil( x )
rounds x to the smallest integer not
less than x
abs( 0.0 ) is 0.0
abs( -23.7 ) is 23.7
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( x )
trigonometric cosine of x (x in radians)
cos( 0.0 ) is 1.0
exp( x )
exponential method ex
floor( x )
rounds x to the largest integer not greater Floor( 9.2 ) is 9.0
than x
floor( -9.8 ) is -10.0
log( x )
natural logarithm of x (base e)
abs( 23.7 ) is 23.7
max( x, y ) larger value of x and y
min( x, y ) smaller value of x and y
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
log( Math.E ) is 1.0
log( Math.E * Math.E ) is 2.0
max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
min( 2.3, 12.7 ) is 2.3
min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to the power y (i.e., xy)
pow( 2.0, 7.0 ) is 128.0
pow( 9.0, 0.5 ) is 3.0
sin( x )
trigonometric sine of x (x in radians)
sin( 0.0 ) is 0.0
sqrt( x )
square root of x
sqrt( 900.0 ) is 30.0
tan( x )
trigonometric tangent of x (x in radians)
tan( 0.0 ) is 0.0
Fig. 6.2
| Math class methods.
 2005 Pearson Education, Inc. All rights reserved.
6.3 static Methods, static Fields and
Class Math (Cont.)
54
• Method main
– main is declared static so it can be invoked without
creating an object of the class containing main
– Any class can contain a main method
• The JVM invokes the main method belonging to the class
specified by the first command-line argument to the java
command
 2005 Pearson Education, Inc. All rights reserved.
55
6.4 Declaring Methods with Multiple
Parameters
• Multiple parameters can be declared by
specifying a comma-separated list.
– Arguments passed in a method call must be consistent with
the number, types and order of the parameters
• Sometimes called formal parameters
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.3: MaximumFinder.java
2
// Programmer-declared method maximum.
3
import java.util.Scanner;
4
5
public class MaximumFinder
6 {
7
8
9
10
11
Outline
// obtain three floating-point values and locate the maximum value
public void determineMaximum()
{
// create Scanner for input from command window
Scanner input = new Scanner( System.in );
12
56
MaximumFinder.java
(1 of 2)
Prompt the user to enter and
read three double values
13
14
15
16
// obtain user input
System.out.print(
"Enter three floating-point values separated by spaces: " );
double number1 = input.nextDouble(); // read first double
17
double number2 = input.nextDouble(); // read second double
18
19
20
21
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum( number1, number2, number3 );
Call method maximum
22
23
24
25
// display maximum value
System.out.println( "Maximum is: " + result );
} // end method determineMaximum
26
Display maximum value
 2005 Pearson Education, Inc. All rights reserved.
27
// returns the maximum of its three double parameters
28
public double maximum( double x, double y, double z )
29
{
30
Outline
57
Declare the maximum method
double maximumValue = x; // assume x is the largest to start
31
•Maximum
Compare y and maximumValue
Finder.java
32
// determine whether y is greater than maximumValue
33
if ( y > maximumValue )
34
maximumValue = y;
35
36
// determine whether z is greater than maximumValue
37
if ( z > maximumValue )
38
maximumValue = z;
•(2 of 2)
Compare z and maximumValue
39
40
return maximumValue;
41
} // end method maximum
Return the maximum value
42 } // end class MaximumFinder
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.4: MaximumFinderTest.java
2
// Application to test class MaximumFinder.
3
4
public class MaximumFinderTest
5
{
6
// application starting point
7
public static void main( String args[] )
8
{
Create a MaximumFinder
object
9
MaximumFinder maximumFinder = new MaximumFinder();
10
maximumFinder.determineMaximum();
11
Outline
58
MaximumFinderTest
.java
Call the determineMaximum
method
} // end main
12 } // end class MaximumFinderTest
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
Enter three floating-point values separated by spaces: 5.8 12.45 8.32
Maximum is: 12.45
Enter three floating-point values separated by spaces: 6.46 4.12 10.54
Maximum is: 10.54
 2005 Pearson Education, Inc. All rights reserved.
59
6.4 Declaring Methods with Multiple
Parameters (Cont.)
• Reusing method Math.max
– The expression Math.max( x, Math.max( y, z ) )
determines the maximum of y and z, and then determines
the maximum of x and that value
• String concatenation
– Using the + operator with two Strings concatenates them
into a new String
– Using the + operator with a String and a value of
another data type concatenates the String with a
String representation of the other value
• When the other value is an object, its toString method is
called to generate its String representation
 2005 Pearson Education, Inc. All rights reserved.
60
6.5 Notes on Declaring and Using
Methods
• Three ways to call a method:
– Use a method name by itself to call another method of the
same class
– Use a variable containing a reference to an object, followed
by a dot (.) and the method name to call a method of the
referenced object
– Use the class name and a dot (.) to call a static method
of a class
•static methods cannot call non-static
methods of the same class directly
 2005 Pearson Education, Inc. All rights reserved.
61
6.6 Method Call Stack and Activation
Records
• Stacks
– Last-in, first-out (LIFO) data structures
• Items are pushed (inserted) onto the top
• Items are popped (removed) from the top
• Program execution stack
– Also known as the method call stack
– Return addresses of calling methods are pushed onto this
stack when they call other methods and popped off when
control returns to them
 2005 Pearson Education, Inc. All rights reserved.
62
6.6 Method Call Stack and Activation
Records (Cont.)
– A method’s local variables are stored in a portion of this
stack known as the method’s activation record or stack
frame
• When the last variable referencing a certain object is popped
off this stack, that object is no longer accessible by the
program
– Will eventually be deleted from memory during
“garbage collection”
• Stack overflow occurs when the stack cannot allocate enough
space for a method’s activation record
 2005 Pearson Education, Inc. All rights reserved.
63
6.7 Argument Promotion and Casting
• Argument promotion
– Java will promote a method call argument to match its
corresponding method parameter according to the
promotion rules
– Values in an expression are promoted to the “highest” type
in the expression (a temporary copy of the value is made)
– Converting values to lower types results in a compilation
error, unless the programmer explicitly forces the
conversion to occur
• Place the desired data type in parentheses before the value
– example: ( int ) 4.5
 2005 Pearson Education, Inc. All rights reserved.
64
Type
Valid promotions
double
float
long
int
char
short
byte
boolean
None
double
float or double
long, float or double
int, long, float or double
int, long, float or double (but not char)
short, int, long, float or double (but not char)
None (boolean values are not considered to be numbers in Java)
| Promotions allowed for
primitive types.
Fig. 6.5
 2005 Pearson Education, Inc. All rights reserved.
65
Common Programming Error 6.9
•Converting a primitive-type value to another
primitive type may change the value if the new
type is not a valid promotion. For example,
converting a floating-point value to an integral
value may introduce truncation errors (loss of
the fractional part) into the result.
 2005 Pearson Education, Inc. All rights reserved.
66
6.8 Java API Packages
• Including the declaration
import java.util.Scanner;
allows the programmer to use Scanner instead
of java.util.Scanner
• Java API documentation
– java.sun.com/j2se/5.0/docs/api/index.html
• Overview of packages in JDK 5.0
– java.sun.com/j2se/5.0/docs/api/overview-summary.html
 2005 Pearson Education, Inc. All rights reserved.
67
Package
Description
java.applet
The Java Applet Package contains a class and several interfaces required to create Java
applets—programs that execute in Web browsers. (Applets are discussed in Chapter 20,
Introduction to Java Applets; interfaces are discussed in Chapter 10, Object_-Oriented
Programming: Polymorphism.)
java.awt
The Java Abstract Window Toolkit Package contains the classes and interfaces required
to create and manipulate GUIs in Java 1.0 and 1.1. In current versions of Java, the Swing
GUI components of the javax.swing packages are often used instead. (Some elements
of the java.awt package are discussed in Chapter 11, GUI Components: Part 1,
Chapter 12, Graphics and Java2D, and Chapter 22, GUI Components: Part 2.)
java.awt.event
The Java Abstract Window Toolkit Event Package contains classes and interfaces that
enable event handling for GUI components in both the java.awt and javax.swing
packages. (You will learn more about this package in Chapter 11, GUI Components: Part
1 and Chapter 22, GUI Components: Part 2.)
java.io
The Java Input/Output Package contains classes and interfaces that enable programs to
input and output data. (You will learn more about this package in Chapter 14, Files and
Streams.)
java.lang
The Java Language Package contains classes and interfaces (discussed throughout this
text) that are required by many Java programs. This package is imported by the compiler
into all programs, so the programmer does not need to do so.
| Java API packages (a
subset). (Part 1 of 2)
Fig. 6.6
 2005 Pearson Education, Inc. All rights reserved.
68
Package
Description
java.net
The Java Networking Package contains classes and interfaces that enable programs to
communicate via computer networks like the Internet. (You will learn more about this in
Chapter 24, Networking.)
java.text
The Java Text Package contains classes and interfaces that enable programs to manipulate
numbers, dates, characters and strings. The package provides internationalization capabilities
that enable a program to be customized to a specific locale (e.g., a program may display strings
in different languages, based on the user’s country).
java.util
The Java Utilities Package contains utility classes and interfaces that enable such actions as date
and time manipulations, random-number processing (class Random), the storing and processing
of large amounts of data and the breaking of strings into smaller pieces called tokens (class
StringTokenizer). (You will learn more about the features of this package in Chapter 19,
Collections.)
javax.swing
The Java Swing GUI Components Package contains classes and interfaces for Java’s Swing
GUI components that provide support for portable GUIs. (You will learn more about this
package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI Components: Part 2.)
javax.swing.event The Java Swing Event Package contains classes and interfaces that enable event handling (e.g.,
responding to button clicks) for GUI components in package javax.swing. (You will learn
more about this package in Chapter 11, GUI Components: Part 1 and Chapter 22, GUI
Components: Part 2.)
| Java API packages (a
subset). (Part 2 of 2)
Fig. 6.6
 2005 Pearson Education, Inc. All rights reserved.
69
Good Programming Practice 6.2
•The online Java API documentation is easy to
search and provides many details about each
class. As you learn a class in this book, you
should get in the habit of looking at the class in
the online documentation for additional
information.
 2005 Pearson Education, Inc. All rights reserved.
70
6.9 Case Study: Random-Number
Generation
• Random-number generation
– static method random from class Math
• Returns doubles in the range 0.0 <= x < 1.0
– class Random from package java.util
• Can produce pseudorandom boolean, byte, float,
double, int, long and Gaussian values
• Is seeded with the current time of day to generate different
sequences of numbers each time the program executes
 2005 Pearson Education, Inc. All rights reserved.
71
6.11 Scope of Declarations
• Basic scope rules
– Scope of a parameter declaration is the body of the method
in which appears
– Scope of a local-variable declaration is from the point of
declaration to the end of that block
– Scope of a local-variable declaration in the initialization
section of a for header is the rest of the for header and
the body of the for statement
– Scope of a method or field of a class is the entire body of
the class
 2005 Pearson Education, Inc. All rights reserved.
72
6.11 Scope of Declarations (Cont.)
• Shadowing
– A field is shadowed (or hidden) if a local variable or
parameter has the same name as the field
• This lasts until the local variable or parameter goes out of
scope
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.11: Scope.java
2
// Scope class demonstrates field and local variable scopes.
Outline
3
4
public class Scope
5
{
6
// field that is accessible to all methods of this class
7
private int x = 1;
•Scope.j
ava
8
9
// method begin creates and initializes local variable x
10
// and calls methods useLocalVariable and useField
11
public void begin()
12
{
13
73
Shadows field x •(1 of 2)
int x = 5; // method's local variable x shadows field x
14
15
System.out.printf( "local x in method begin is %d\n", x );
Display value of
local variable x
16
17
useLocalVariable(); // useLocalVariable has local x
18
useField(); // useField uses class Scope's field x
19
useLocalVariable(); // useLocalVariable reinitializes local x
20
21
useField(); // class Scope's field x retains its value
 2005 Pearson Education, Inc. All rights reserved.
22
23
System.out.printf( "\nlocal x in method begin is %d\n", x );
Outline
} // end method begin
24
25
// create and initialize local variable x during each call
26
public void useLocalVariable()
27
{
28
Shadows field x
int x = 25; // initialized each time useLocalVariable is called
29
30
System.out.printf(
31
"\nlocal x on entering method useLocalVariable is %d\n", x );
32
++x; // modifies this method's local variable x
33
System.out.printf(
34
35
"local x before exiting method useLocalVariable is %d\n", x );
74
•Scope.j
ava
•(2 of 2)
Display value of
local variable x
} // end method useLocalVariable
36
37
// modify class Scope's field x during each call
38
public void useField()
39
{
40
41
System.out.printf(
"\nfield x on entering method useField is %d\n", x );
42
x *= 10; // modifies class Scope's field x
43
System.out.printf(
44
45
Display value of
field x
"field x before exiting method useField is %d\n", x );
} // end method useField
46 } // end class Scope
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.12: ScopeTest.java
2
// Application to test class Scope.
3
4
public class ScopeTest
5
{
6
// application starting point
7
public static void main( String args[] )
8
{
9
Scope testScope = new Scope();
10
testScope.begin();
11
Outline
75
•ScopeTe
st.java
} // end main
12 } // end class ScopeTest
local x in method begin is 5
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 1
field x before exiting method useField is 10
local x on entering method useLocalVariable is 25
local x before exiting method useLocalVariable is 26
field x on entering method useField is 10
field x before exiting method useField is 100
local x in method begin is 5
 2005 Pearson Education, Inc. All rights reserved.
76
6.12 Method Overloading
• Method overloading
– Multiple methods with the same name, but different types,
number or order of parameters in their parameter lists
– Compiler decides which method is being called by
matching the method call’s argument list to one of the
overloaded methods’ parameter lists
• A method’s name and number, type and order of its
parameters form its signature
– Differences in return type are irrelevant in method
overloading
• Overloaded methods can have different return types
• Methods with different return types but the same signature
cause a compilation error
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Fig. 6.13: MethodOverload.java
// Overloaded method declarations.
public class MethodOverload
Correctly calls the
{
// test overloaded square methods
public void testOverloadedMethods()
{
System.out.printf( "Square of integer 7 is %d\n", square( 7 ) );
System.out.printf( "Square of double 7.5 is %f\n", square( 7.5 ) );
} // end method testOverloadedMethods
Outline
“square of int” method
77
•Method
Correctly calls the “square ofOverloa
double” method
d.java
// square method with int argument
public int square( int intValue )
{
System.out.printf( "\nCalled square with int argument: %d\n",
intValue );
return intValue * intValue;
} // end method square with int argument
Declaring the “square of
int” method
// square method with double argument
public double square( double doubleValue )
{
System.out.printf( "\nCalled square with double argument: %f\n",
doubleValue );
return doubleValue * doubleValue;
} // end method square with double argument
} // end class MethodOverload
Declaring the “square of
double” method
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.14: MethodOverloadTest.java
2
// Application to test class MethodOverload.
3
4
public class MethodOverloadTest
5
{
6
public static void main( String args[] )
7
{
8
MethodOverload methodOverload = new MethodOverload();
9
methodOverload.testOverloadedMethods();
10
} // end main
11 } // end class MethodOverloadTest
Called square with int argument: 7
Square of integer 7 is 49
Outline
78
•MethodOv
erloadTest.
java
Called square with double argument: 7.500000
Square of double 7.5 is 56.250000
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 6.15: MethodOverloadError.java
2
// Overloaded methods with identical signatures
3
4
5
// cause compilation errors, even if return types are different.
6
{
7
8
9
Outline
79
public class MethodOverloadError
•MethodOv
erload
// declaration of method square with int argument
public int square( int x )
{
return x * x;
10
11
12
}
13
14
15
16
// second declaration of method square with int argument
// causes compilation error even though return types are different
public double square( int y )
{
•Error.java
Same method signature
17
return y * y;
18
}
19 } // end class MethodOverloadError
MethodOverloadError.java:15: square(int) is already defined in
MethodOverloadError
public double square( int y )
^
Compilation
1 error
error
 2005 Pearson Education, Inc. All rights reserved.
80
Common Programming Error 6.11
•Declaring overloaded methods with identical
parameter lists is a compilation error
regardless of whether the return types are
different.
 2005 Pearson Education, Inc. All rights reserved.
81
7.1 Introduction
• Arrays
– Data structures
– Related data items of same type
– Remain same size once created
• Fixed-length entries
 2005 Pearson Education, Inc. All rights reserved.
82
7.2 Arrays
• Array
– Group of variables
• Have same type
– Reference type
 2005 Pearson Education, Inc. All rights reserved.
83
Fig. 7.1
| A 12-element array.
 2005 Pearson Education, Inc. All rights reserved.
84
7.2 Arrays (Cont.)
• Index
– Also called subscript
– Position number in square brackets
– Must be positive integer or integer expression
– First element has index zero
a = 5;
b = 6;
c[ a + b ] += 2;
• Adds 2 to c[ 11 ]
 2005 Pearson Education, Inc. All rights reserved.
85
Common Programming Error 7.1
•Using a value of type long as an array index
results in a compilation error. An index must be
an int value or a value of a type that can be
promoted to int—namely, byte, short or char,
but not long.
 2005 Pearson Education, Inc. All rights reserved.
86
7.2 Arrays (Cont.)
• Examine array c
– c is the array name
– c.length accesses array c’s length
– c has 12 elements ( c[0], c[1], … c[11] )
• The value of c[0] is –45
 2005 Pearson Education, Inc. All rights reserved.
87
7.3 Declaring and Creating Arrays
• Declaring and Creating arrays
– Arrays are objects that occupy memory
– Created dynamically with keyword new
int c[] = new int[ 12 ];
– Equivalent to
int c[]; // declare array variable
c = new int[ 12 ]; // create array
• We can create arrays of objects too
String b[] = new String[ 100 ];
 2005 Pearson Education, Inc. All rights reserved.
88
7.4 Examples Using Arrays
• Declaring arrays
• Creating arrays
• Initializing arrays
• Manipulating array elements
 2005 Pearson Education, Inc. All rights reserved.
89
7.4 Examples Using Arrays
• Creating and initializing an array
– Declare array
– Create array
– Initialize array elements
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.2: InitArray.java
// Creating an array.
3
4
5
6
public class InitArray
Declare array as
{
array
public static void main( String args[]
) of ints
7
8
9
10
11
12
Outline
an
Create 10 ints for array; each
int is initialized to 0 by default
{
int array[]; // declare array named array
array.length returns
length of array
array = new int[ 10 ]; // create the space for array
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
13
14
// output each array element's value
15
for ( int counter = 0; counter < array.length; counter++ )
16
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
17
} // end main
18 } // end class InitArray
Index
0
1
2
3
4
5
6
7
8
9
Value
0
0
0
0
0
0
0
0
0
0
90
Each int is initialized
to 0 by default
•InitArr
ay.java
•Line 8
Declare array as an
array of ints
Line 10
Create 10 ints for
array; each int is
initialized to 0 by
default
Line 15
array.length returns
length of array
array[counter] returns int
associated with index in array
Line 16
array[counter]
returns int associated
with index in array
•Program output
 2005 Pearson Education, Inc. All rights reserved.
91
7.4 Examples Using Arrays (Cont.)
• Using an array initializer
– Use initializer list
• Items enclosed in braces ({})
• Items in list separated by commas
int n[] = { 10, 20, 30, 40, 50 };
– Creates a five-element array
– Index values of 0, 1, 2, 3, 4
– Do not need keyword new
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.3: InitArray.java
// Initializing the elements of an array with an array initializer.
3
4
5
public class InitArray
{
6
public static void main( String args[] )
7
8
9
10
11
12
{
13
14
15
16
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
// output each array element's value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end main
Value
32
27
64
18
95
14
90
70
60
37
Outline
Compiler uses initializer list
to allocate array
// initializer list specifies the value for each element
int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
17 } // end class InitArray
Index
0
1
2
3
4
5
6
7
8
9
Declare array as an
array of ints
92
•InitArr
ay.java
•Line 9
Declare array as an
array of ints
Line 9
Compiler uses
initializer list to
allocate array
•Program output
 2005 Pearson Education, Inc. All rights reserved.
93
7.4 Examples Using Arrays (Cont.)
• Calculating a value to store in each array element
– Initialize elements of 10-element array to even integers
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 7.4: InitArray.java
// Calculating values to be placed into elements of an array.
Outline
94
public class InitArray
Declare constant variable ARRAY_LENGTH
{
using the final modifier
public static void main( String args[] )
{
final int ARRAY_LENGTH = 10; // declare constant
Declare and create array
int array[] = new int[ ARRAY_LENGTH ]; // create array
•InitArr
that contains 10 ints ay.java
// calculate value for each array element
for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = 2 + 2 * counter;
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
// output each array element's value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
Use array index to
} // end main
assign array value
} // end class InitArray
Index
0
1
2
3
4
5
6
7
8
9
Value
2
4
6
8
10
12
14
16
18
20
•Line 8
Declare constant
variable
•Line 9
Declare and create
array that contains 10
ints
•
Line 13
Use array index to
assign array
•Program output
 2005 Pearson Education, Inc. All rights reserved.
95
7.4 Examples Using Arrays (Cont.)
• Summing the elements of an array
– Array elements can represent a series of values
• We can sum these values
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 7.5: SumArray.java
2
// Computing the sum of the elements of an array.
3
4
public class SumArray
5
{
6
public static void main( String args[] )
7
{
Declare array with
initializer list
8
int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
9
int total = 0;
10
11
// add each element's value to total
12
for ( int counter = 0; counter < array.length; counter++ )
13
16
•SumArra
y.java
•Line 8
Declare array with
initializer list
total += array[ counter ];
Sum all array values
14
15
Outline
96
System.out.printf( "Total of array elements: %d\n",
total );
Lines 12-13
Sum all array values
} // end main
17 } // end class SumArray
Total of array elements: 849
•Program output
 2005 Pearson Education, Inc. All rights reserved.
97
7.6 Enhanced for Statement
• Enhanced for statement
– New feature of J2SE 5.0
– Allows iterates through elements of an array or a collection
without using a counter
– Syntax
for ( parameter : arrayName )
statement
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.12: EnhancedForTest.java
// Using enhanced for statement to total integers in an array.
Outline
3
4
5
6
7
8
9
10
11
12
13
14
15
public class EnhancedForTest
{
public static void main( String args[] )
{
98
•Enhance
dForTest.
For each iteration, assign the next
element of array to int variable
java
number, then add it to total
int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
// add each element's value to total
for ( int number : array )
total += number;
System.out.printf( "Total of array elements: %d\n", total );
16
} // end main
17 } // end class EnhancedForTest
Total of array elements: 849
 2005 Pearson Education, Inc. All rights reserved.
99
7.6 Enhanced for Statement (Cont.)
• Lines 12-13 are equivalent to
for ( int counter = 0; counter < array.length; counter++ )
total += array[ counter ];
• Usage
– Can access array elements
– Cannot modify array elements
– Cannot access the counter indicating the index
 2005 Pearson Education, Inc. All rights reserved.
100
7.7 Passing Arrays to Methods
• To pass array argument to a method
– Specify array name without brackets
• Array hourlyTemperatures is declared as
int hourlyTemperatures = new int[ 24 ];
• The method call
modifyArray( hourlyTemperatures );
• Passes array hourlyTemperatures to method
modifyArray
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 7.13: PassArray.java
2
3
// Passing arrays and individual array elements to methods.
4
5
6
7
8
9
public class PassArray
{
// main creates array and calls modifyArray and modifyElement
public static void main( String args[] )
{
int array[] = { 1, 2, 3, 4, 5 };
Declare 5-int array
with initializer list
10
11
12
13
14
System.out.println(
"Effects of passing reference to entire
"The values of the original array are:"
15
16
// output original array elements
for ( int value : array )
17
18
•PassArr
ay.java
Pass entire array to method
•(1 of 2)
modifyArray
array:\n" +
•Line 9
);
•Line 19
System.out.printf( "
%d", value );
19
20
21
22
modifyArray( array ); // pass array reference
System.out.println( "\n\nThe values of the modified array are:" );
23
for ( int value : array )
24
25
26
27
System.out.printf( "
28
Outline
101
// output modified array elements
%d", value );
System.out.printf(
"\n\nEffects of passing array element value:\n" +
"array[3] before modifyElement: %d\n", array[ 3 ] );
 2005 Pearson Education, Inc. All rights reserved.
29
30
modifyElement( array[ 3 ] ); // attempt to modify array[ 3 ]
31
System.out.printf(
Pass array element array[3] to
32
"array[3] after modifyElement: %d\n", array[ 3 ] );
method modifyElement
33
} // end main
34
35
// multiply each element of an array by 2
Method modifyArray
36
public static void modifyArray( int array2[] )
manipulates the array directly
37
{
38
for ( int counter = 0; counter < array2.length; counter++ )
39
array2[ counter ] *= 2;
Method modifyElement
40
} // end method modifyArray
•(2 of 2)
41
manipulates a primitive’s copy
•Line 30
42
// multiply argument by 2
43
public static void modifyElement( int element )
•Lines 36-40
44
{
•Lines 43-48
45
element *= 2;
46
System.out.printf(
47
"Value of element in modifyElement: %d\n", element );
48
} // end method modifyElement
49 } // end class PassArray
Outline
102
•PassArr
ay.java
•Program output
Effects of passing reference to entire array:
The values of the original array are:
1
2
3
4
5
The values of the modified array are:
2
4
6
8
10
Effects of passing array element value:
array[3] before modifyElement: 8
Value of element in modifyElement: 16
array[3] after modifyElement: 8
 2005 Pearson Education, Inc. All rights reserved.
103
7.7 Passing Arrays to Methods (Cont.)
• Notes on passing arguments to methods
– Two ways to pass arguments to methods
• Pass-by-value
– Copy of argument’s value is passed to called method
– In Java, every primitive is pass-by-value
• Pass-by-reference
–
–
–
–
Caller gives called method direct access to caller’s data
Called method can manipulate this data
Improved performance over pass-by-value
In Java, every object is pass-by-reference
• In Java, arrays are objects
• Therefore, arrays are passed to methods by reference
 2005 Pearson Education, Inc. All rights reserved.
104
7.8 Case Study: Class GradeBook Using
an Array to Store Grades
• Further evolve class GradeBook
• Class GradeBook
– Represent a grade book that stores and analyzes grades
– Does not maintain individual grade values
– Repeat calculations require reentering the same grades
• Can be solved by storing grades in an array
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.14: GradeBook.java
// Grade book using an array to store test grades.
3
4
5
public class GradeBook
{
Outline
6
7
8
9
private String courseName; // name of course this GradeBook represents
private int grades[]; // array of student grades
10
11
public GradeBook( String name, int gradesArray[] )
{
// two-argument constructor initializes courseName and grades array
12
13
courseName = name; // initialize courseName
grades = gradesArray; // store grades
14
} // end two-argument GradeBook constructor
15
16
17
// method to set the course name
public void setCourseName( String name )
18
19
20
105
•GradeB
ook.java
Declare array grades to
store individual grades •(1 of 5)
•Line 7
•Line 13
Assign the array’s reference
to instance variable grades
{
courseName = name; // store the course name
} // end method setCourseName
21
22
// method to retrieve the course name
23
24
public String getCourseName()
{
25
26
27
return courseName;
} // end method getCourseName
 2005 Pearson Education, Inc. All rights reserved.
28
// display a welcome message to the GradeBook user
29
public void displayMessage()
30
{
31
32
33
34
35
36
37
38
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
getCourseName() );
} // end method displayMessage
Outline
// perform various operations on the data
public void processGrades()
{
106
•GradeB
ook.java
•(2 of 5)
39
// output grades array
40
41
outputGrades();
42
43
44
// call method getAverage to calculate the average grade
System.out.printf( "\nClass average is %.2f\n", getAverage() );
45
46
47
48
// call methods getMinimum and getMaximum
System.out.printf( "Lowest grade is %d\nHighest grade is %d\n\n",
getMinimum(), getMaximum() );
49
50
// call outputBarChart to print grade distribution chart
outputBarChart();
51
52
} // end method processGrades
53
// find minimum grade
54
55
56
57
public int getMinimum()
{
int lowGrade = grades[ 0 ]; // assume grades[ 0 ] is smallest
 2005 Pearson Education, Inc. All rights reserved.
58
// loop through grades array
59
for ( int grade : grades )
60
{
// if grade lower than lowGrade, assign it to lowGrade
if ( grade < lowGrade )
Loop through
61
62
lowGrade = grade; // new lowest grade
63
} // end for
64
65
66
67
Outline
grades to
find the lowest grade
return lowGrade; // return lowest grade
} // end method getMinimum
69
70
// find maximum grade
public int getMaximum()
71
{
•Lines 59-64
•Lines 75-80
72
int highGrade = grades[ 0 ]; // assume grades[ 0 ] is largest
73
74
// loop through grades array
75
for ( int grade : grades )
76
77
{
80
81
82
83
84
•GradeB
ook.java
•(3 of 5)
68
78
79
107
// if grade greater than highGrade, assign it to highGrade
if ( grade > highGrade )
highGrade = grade; // new highest grade
} // end for
Loop through grades to
find the highest grade
return highGrade; // return highest grade
} // end method getMaximum
 2005 Pearson Education, Inc. All rights reserved.
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// determine average grade for test
public double getAverage()
{
int total = 0; // initialize total
Outline
// sum grades for one student
for ( int grade : grades )
total += grade;
// return average of grades
return (double) total / grades.length;
} // end method getAverage
108
•GradeB
ook.java
Loop through grades to
sum grades for one student •(4 of 5)
•Lines 91-92
// output bar chart displaying grade distribution
public void outputBarChart()
{
System.out.println( "Grade distribution:" );
•Lines 107-108
// stores frequency of grades in each range of 10 grades
int frequency[] = new int[ 11 ];
// for each grade, increment the appropriate frequency
for ( int grade : grades )
++frequency[ grade / 10 ];
Loop through grades to
calculate frequency
 2005 Pearson Education, Inc. All rights reserved.
110
// for each grade frequency, print bar in chart
111
112
for ( int count = 0; count < frequency.length; count++ )
{
Outline
113
// output bar label ( "00-09: ", ..., "90-99: ", "100: " )
114
115
116
117
if ( count == 10 )
System.out.printf( "%5d: ", 100 );
else
System.out.printf( "%02d-%02d: ",
118
count * 10, count * 10 + 9
•GradeB
ook.java
);
119
120
121
122
// print bar of asterisks
for ( int stars = 0; stars < frequency[ count ]; stars++ )
System.out.print( "*" );
123
124
System.out.println(); // start a new line of output
125
126
} // end outer for
} // end method outputBarChart
127
128
129
// output the contents of the grades array
public void outputGrades()
130
131
109
•(5 of 5)
•Lines 134-136
Loop through grades to
display each grade
{
System.out.println( "The grades are:\n" );
132
133
// output each student's grade
134
135
136
for ( int student = 0; student < grades.length; student++ )
System.out.printf( "Student %2d: %3d\n",
student + 1, grades[ student ] );
137
} // end method outputGrades
138 } // end class GradeBook
 2005 Pearson Education, Inc. All rights reserved.
110
7.9 Multidimensional Arrays
• Multidimensional arrays
– Tables with rows and columns
• Two-dimensional array
• m-by-n array
 2005 Pearson Education, Inc. All rights reserved.
111
| Two-dimensional array with three
rows and four columns.
Fig. 7.16
 2005 Pearson Education, Inc. All rights reserved.
112
7.9 Multidimensional Arrays (Cont.)
• Arrays of one-dimensional array
– Declaring two-dimensional array b[2][2]
int b[][] = { { 1, 2 }, { 3, 4 } };
– 1 and 2 initialize b[0][0] and b[0][1]
– 3 and 4 initialize b[1][0] and b[1][1]
int b[][] = { { 1, 2 }, { 3, 4, 5 } };
– row 0 contains elements 1 and 2
– row 1 contains elements 3, 4 and 5
 2005 Pearson Education, Inc. All rights reserved.
113
7.9 Multidimensional Arrays (Cont.)
• Two-dimensional arrays with rows of different
lengths
– Lengths of rows in array are not required to be the same
• E.g., int b[][] = { { 1, 2 }, { 3, 4, 5 } };
 2005 Pearson Education, Inc. All rights reserved.
114
7.9 Multidimensional Arrays (Cont.)
• Creating two-dimensional arrays with arraycreation expressions
– Can be created dynamically
• 3-by-4 array
int b[][];
b = new int[ 3 ][ 4 ];
• Rows can have different number of columns
int b[][];
b = new int[ 2 ][ ];
// create 2 rows
b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0
b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Fig. 7.17: InitArray.java
// Initializing two-dimensional arrays.
public class InitArray
{
// create and output two-dimensional arrays
Outline
Use nested array initializers
to initialize array1
public static void main( String args[] )
{
int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; Use nested array initializers
int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; of different lengths to
initialize array2
System.out.println( "Values in array1 by row are" );
outputArray( array1 ); // displays array1 by row
115
•InitArra
y.java
•(1 of 2)
•Line 9
•Line 10
System.out.println( "\nValues in array2 by row are" );
outputArray( array2 ); // displays array2 by row
} // end main
 2005 Pearson Education, Inc. All rights reserved.
19
// output rows and columns of a two-dimensional array
20
21
public static void outputArray( int array[][] )
{
array[row].length
22
23
24
25
26
27
returns number
of columns associated with row subscript
// loop through array's rows
for ( int row = 0; row < array.length; row++ )
{
// loop through columns of current row
for ( int column = 0; column < array[ row ].length; column++ )
System.out.printf( "%d ", array[ row ][ column ] );
28
29
30
Outline
116
System.out.println(); // start new line of output
} // end outer for
31
} // end method outputArray
32 } // end class InitArray
Values in array1 by row are
1 2 3
4 5 6
•InitArra
y.java
•(2 of 2)
•Line 26
Use double-bracket notation to access
two-dimensional array values •Line 27
•Program output
Values in array2 by row are
1 2
3
4 5 6
 2005 Pearson Education, Inc. All rights reserved.
117
7.9 Multidimensional Arrays (Cont.)
• Common multidimensional-array manipulations
performed with for statements
– Many common array manipulations use for statements
E.g.,
for ( int column = 0; column < a[ 2 ].length; column++ )
a[ 2 ][ column ] = 0;
 2005 Pearson Education, Inc. All rights reserved.
7.10 Case Study: Class GradeBook Using
a Two-Dimensional Array
118
• Class GradeBook
– One-dimensional array
• Store student grades on a single exam
– Two-dimensional array
• Store grades for a single student and for the class as a whole
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.18: GradeBook.java
// Grade book using a two-dimensional array to store grades.
3
4
5
public class GradeBook
{
Declare two-dimensional array grades
6
private String courseName; // name of course this grade book represents
7
8
9
private int grades[][]; // two-dimensional array of student grades
// two-argument constructor initializes courseName and grades array
10
public GradeBook( String name, int gradesArray[][] )
11
12
{
13
14
grades = gradesArray; // store grades
} // end two-argument GradeBook constructor
15
16
17
18
// method to set the course name
public void setCourseName( String name )
{
Outline
119
•GradeB
ook.java
•(1 of 7)
courseName = name; // initialize courseName
19
20
21
22
courseName = name; // store the course name
} // end method setCourseName
23
24
25
26
public String getCourseName()
{
return courseName;
} // end method getCourseName
•Line 7
GradeBook constructor
accepts a String and a
two-dimensional array
•Line 10
// method to retrieve the course name
27
 2005 Pearson Education, Inc. All rights reserved.
28
// display a welcome message to the GradeBook user
29
30
31
32
public void displayMessage()
{
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
33
34
35
getCourseName() );
} // end method displayMessage
36
37
38
// perform various operations on the data
public void processGrades()
{
Outline
120
•GradeB
ook.java
•(2 of 7)
39
40
41
// output grades array
outputGrades();
42
// call methods getMinimum and getMaximum
43
44
45
System.out.printf( "\n%s %d\n%s %d\n\n",
"Lowest grade in the grade book is", getMinimum(),
"Highest grade in the grade book is", getMaximum() );
46
47
48
// output grade distribution chart of all grades on all tests
outputBarChart();
49
50
51
} // end method processGrades
52
53
54
public int getMinimum()
{
// assume first element of grades array is smallest
55
56
// find minimum grade
int lowGrade = grades[ 0 ][ 0 ];
 2005 Pearson Education, Inc. All rights reserved.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// loop through rows of grades array
for ( int studentGrades[] : grades )
{
// loop through columns of current row
for ( int grade : studentGrades )
Loop through rows of grades to find
{
the lowest
of any student
// if grade less than lowGrade, assign
it tograde
lowGrade
if ( grade < lowGrade )
lowGrade = grade;
} // end inner for
} // end outer for
return lowGrade; // return lowest grade
} // end method getMinimum
Outline
121
•GradeB
ook.java
•(3 of 7)
•Lines 58-67
// find maximum grade
public int getMaximum()
{
// assume first element of grades array is largest
int highGrade = grades[ 0 ][ 0 ];
 2005 Pearson Education, Inc. All rights reserved.
78
79
80
81
// loop through rows of grades array
for ( int studentGrades[] : grades )
{
// loop through columns of current row
82
for ( int grade : studentGrades )
83
84
85
86
87
88
{
// if grade greater than
if ( grade > highGrade )
highGrade = grade;
} // end inner for
} // end outer for
89
90
return highGrade; // return highest grade
91
92
93
94
95
96
97
98
99
100
Outline
Loop through rows of grades to find
the highest
any student
highGrade,
assigngrade
it to of
highGrade
122
•GradeB
ook.java
•(4 of 7)
•Lines 79-88
•Lines 94-104
} // end method getMaximum
// determine average grade for particular set of grades
public double getAverage( int setOfGrades[] )
{
int total = 0; // initialize total
// sum grades for one student
for ( int grade : setOfGrades )
total += grade;
Calculate a particular student’s
semester average
101
102
103
104
// return average of grades
return (double) total / setOfGrades.length;
} // end method getAverage
105
 2005 Pearson Education, Inc. All rights reserved.
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// output bar chart displaying overall grade distribution
public void outputBarChart()
{
System.out.println( "Overall grade distribution:" );
Outline
// stores frequency of grades in each range of 10 grades
int frequency[] = new int[ 11 ];
// for each grade in GradeBook, increment the appropriate frequency
for ( int studentGrades[] : grades )
{
for ( int grade : studentGrades )
++frequency[ grade / 10 ];
Calculate the distribution of
} // end outer for
123
•GradeB
ook.java
•(5 of 7)
•Lines 115-119
all student grades
// for each grade frequency, print bar in chart
for ( int count = 0; count < frequency.length; count++ )
{
// output bar label ( "00-09: ", ..., "90-99: ", "100: " )
if ( count == 10 )
System.out.printf( "%5d: ", 100 );
else
System.out.printf( "%02d-%02d: ",
count * 10, count * 10 + 9 );
// print bar of asterisks
for ( int stars = 0; stars < frequency[ count ]; stars++ )
System.out.print( "*" );
 2005 Pearson Education, Inc. All rights reserved.
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
System.out.println(); // start a new line of output
} // end outer for
} // end method outputBarChart
// output the contents of the grades array
public void outputGrades()
{
System.out.println( "The grades are:\n" );
System.out.print( "
" ); // align column heads
// create a column heading for each of the tests
for ( int test = 0; test < grades[ 0 ].length; test++ )
System.out.printf( "Test %d ", test + 1 );
Outline
124
•GradeB
ook.java
•(6 of 7)
System.out.println( "Average" ); // student average column heading
// create rows/columns of text representing array grades
for ( int student = 0; student < grades.length; student++ )
{
System.out.printf( "Student %2d", student + 1 );
for ( int test : grades[ student ] ) // output student's grades
System.out.printf( "%8d", test );
 2005 Pearson Education, Inc. All rights reserved.
159
// call method getAverage to calculate student's average grade;
160
161
// pass row of grades as the argument to getAverage
double average = getAverage( grades[ student ] );
162
163
164
165
Outline
125
System.out.printf( "%9.2f\n", average );
} // end outer for
} // end method outputGrades
} // end class GradeBook
•GradeB
ook.java
•(7 of 7)
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 7.19: GradeBookTest.java
// Creates GradeBook object using a two-dimensional array of grades.
public class GradeBookTest
{
// main method begins program execution
public static void main( String args[] )
{
// two-dimensional array of student grades
int gradesArray[][] = { { 87, 96, 70 },
{ 68, 87, 90 },
{ 94, 100, 90 },
{ 100, 81, 82 },
{ 83, 65, 85 },
{ 78, 87, 65 },
{ 85, 75, 83 },
{ 91, 94, 100 },
{ 76, 72, 84 },
{ 87, 93, 73 } };
Outline
126
Declare gradesArray as 3by-10 array
•GradeB
ookTest
•.java
•(1 of 2)
•Lines 10-19
Each row represents a student; each
grade
GradeBook myGradeBook = new GradeBook(
column represents
"CS101 Introduction to Java Programming",
gradesArrayan);exam
myGradeBook.displayMessage();
myGradeBook.processGrades();
} // end main
} // end class GradeBookTest
 2005 Pearson Education, Inc. All rights reserved.
Welcome to the grade book for
CS101 Introduction to Java Programming!
Outline
127
The grades are:
Student 1
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Student 8
Student 9
Student 10
Test 1
87
68
94
100
83
78
85
91
76
87
Test 2
96
87
100
81
65
87
75
94
72
93
Test 3
70
90
90
82
85
65
83
100
84
73
Average
84.33
81.67
94.67
87.67
77.67
76.67
81.00
95.00
77.33
84.33
Lowest grade in the grade book is 65
Highest grade in the grade book is 100
Overall grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69:
70-79:
80-89:
90-99:
100:
•GradeB
ookTest
•.java
•(2 of 2)
•Program output
***
******
***********
*******
***
 2005 Pearson Education, Inc. All rights reserved.
128
7.11 Variable-Length Argument Lists
• Variable-length argument lists
– New feature in J2SE 5.0
– Unspecified number of arguments
– Use ellipsis (…) in method’s parameter list
• Can occur only once in parameter list
• Must be placed at the end of parameter list
– Array whose elements are all of the same type
 2005 Pearson Education, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 7.20: VarargsTest.java
// Using variable-length argument lists.
Outline
public class VarargsTest
{
// calculate average
public static double average( double... numbers )
{
double total = 0.0; // initialize total
Method
average receives a variable
// calculate total using the enhanced
for statement
for ( double d : numbers )
length sequence of doubles
total += d;
return total / numbers.length;
Calculate
} // end method average
the total of the
doubles in the array
public static void main( String args[] )
Access numbers.length
{
the size of the numbers
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;
to obtain
array
129
•Varargs
Test
•.java
•(1 of 2)
•Line 7
•Lines 12-13
•Line 15
 2005 Pearson Education, Inc. All rights reserved.
25
26
System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n",
d1, d2, d3, d4 );
27
28
29
System.out.printf( "Average of d1 and d2 is %.1f\n",
average( d1, d2 ) );
30
31
32
System.out.printf( "Average of d1, d2 and d3 is %.1f\n",
two arguments
average( d1, d2, d3 ) );
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n",
Invoke method average with
33
average( d1, d2, d3, d4 ) );
34
} // end main
35 } // end class VarargsTest
d1
d2
d3
d4
Outline
130
=
=
=
=
Invoke method average with
three arguments
•.java
10.0
20.0
30.0
40.0
Average of d1 and d2 is 15.0
Average of d1, d2 and d3 is 20.0
Average of d1, d2, d3 and d4 is 25.0
•Varargs
Test
•(2 of 2)
•Line 29
Invoke method average with
four arguments
•Line 31
•Line 33
•Program output
 2005 Pearson Education, Inc. All rights reserved.
131
Common Programming Error 7.6
•Placing an ellipsis in the middle of a method
parameter list is a syntax error. An ellipsis may
be placed only at the end of the parameter list.
 2005 Pearson Education, Inc. All rights reserved.
132
7.12 Using Command-Line Arguments
• Command-line arguments
– Pass arguments from the command line
• String args[]
– Appear after the class name in the java command
• java MyClass a b
– Number of arguments passed in from command line
• args.length
– First command-line argument
• args[ 0 ]
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 7.21: InitArray.java
// Using command-line arguments to initialize an array.
Outline
3
4
5
133
public class InitArray
{
6
public static void main( String args[] )
7
8
{
•InitArra
y.java
// check number of command-line arguments
9
10
11
12
if ( args.length != 3 )
Array args stores commandSystem.out.println(
linecommand,
arguments
"Error: Please re-enter the entire
including\n" +
"an array size, initial value and increment." );
13
14
else
{
•(1 of 2)
•Line 6
•Line 9
•Line 16
•Lines 20-21
•Lines 24-25
Check number of arguments
passed in from the command line
15
16
17
18
// get array size from first command-line argument
int arrayLength = Integer.parseInt( args[ 0 ] );
int array[] = new int[ arrayLength ]; // create array
19
20
21
22
23
// get initial value and increment from command-line argument
Obtain first command-line
int initialValue = Integer.parseInt( args[ 1 ] );
int increment = Integer.parseInt( args[ 2 ] );
24
25
for ( int counter = 0; counter < array.length; counter++
)
Obtain second
array[ counter ] = initialValue + increment * counter;
26
27
28
System.out.printf( "%s%8s\n", "Index", "Value" );
argument
// calculate value for each array element
and third
command-line arguments
Calculate the value for each array element
based on command-line arguments
 2005 Pearson Education, Inc. All rights reserved.
29
// display array index and value
30
for ( int counter = 0; counter < array.length; counter++ )
31
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
32
} // end else
33
} // end main
34 } // end class InitArray
java InitArray
Error: Please re-enter the entire command, including
an array size, initial value and increment.
Missing
arguments
java InitArray
5 0 command-line
4
Index
Value
0
0
1
4
2
8
3
12
Three command-line arguments
4
16
Outline
134
•InitArra
y.java
•(2 of 2)
•Program output
are
5, 0 and 4
java InitArray 10 1 2
Index
Value
0
1
1
3
2
5
3
7
Three
4
9
5
11
6
13
7
15
8
17
9
19
command-line arguments are
10, 1 and 2
 2005 Pearson Education, Inc. All rights reserved.
135
8.2 Time Class Case Study
•public services (or public interface)
– public methods available for a client to use
• If a class does not define a constructor the
compiler will provide a default constructor
• Instance variables
– Can be initialized when they are declared or in a
constructor
– Should maintain consistent (valid) values
 2005 Pearson Education, Inc. All rights reserved.
136
Software Engineering Observation 8.1
•Methods that modify the values of private
variables should verify that the intended new
values are proper. If they are not, the set methods
should place the private variables into an
appropriate consistent state.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.1: Time1.java
2
// Time1 class declaration maintains the time in 24-hour format.
3
4
public class Time1
5
{
Outline
137
private instance variables
6
private int hour;
7
private int minute; // 0 - 59
8
private int second; // 0 - 59
•Time1.jav
a
// 0 – 23
9
•(1 of 2)
10
// set a new time value using universal time; ensure that
11
// the data remains consistent by setting invalid values to zero
12
public void setTime( int h, int m, int s )
Declare public method setTime
13
14
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
15
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute
16
second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second
17
// validate hour
} // end method setTime
18
Validate parameter values before setting
instance variables
 2005 Pearson Education, Inc. All rights reserved.
19
// convert to String in universal-time format (HH:MM:SS)
20
public String toUniversalString()
21
{
return String.format( "%02d:%02d:%02d", hour, minute, second );
22
23
Outline
} // end method toUniversalString
format strings
24
25
// convert to String in standard-time format (H:MM:SS AM or PM)
26
public String toString()
27
{
28
•Time1.jav
a
return String.format( "%d:%02d:%02d %s",
29
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
30
minute, second, ( hour < 12 ? "AM" : "PM" ) );
31
138
•(2 of 2)
} // end method toString
32 } // end class Time1
 2005 Pearson Education, Inc. All rights reserved.
139
8.2 Time Class Case Study (Cont.)
•String method format
– Similar to printf except it returns a formatted string
instead of displaying it in a command window
•new implicitly invokes Time1’s default
constructor since Time1 does not declare any
constructors
 2005 Pearson Education, Inc. All rights reserved.
140
Software Engineering Observation 8.2
•Classes simplify programming, because the client
can use only the public methods exposed by the
class. Such methods are usually client oriented
rather than implementation oriented. Clients are
neither aware of, nor involved in, a class’s
implementation. Clients generally care about what
the class does but not how the class does it.
 2005 Pearson Education, Inc. All rights reserved.
141
Software Engineering Observation 8.3
•Interfaces change less frequently than
implementations. When an implementation
changes, implementation-dependent code
must change accordingly. Hiding the
implementation reduces the possibility that
other program parts will become dependent
on class-implementation details.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.2: Time1Test.java
2
3
// Time1 object used in an application.
4
public class Time1Test
5
6
7
8
9
{
Outline
public static void main( String args[] )
Create a Time1
{
// create and initialize a Time1 object
Time1 time = new Time1(); // invokes Time1 constructor
10
11
// output string representations of the time
12
13
System.out.print( "The initial universal time is: " );
System.out.println( time.toUniversalString() );
14
15
16
System.out.print( "The initial standard time is: " );
System.out.println( time.toString() );
System.out.println(); // output a blank line
object
142
•Time1Test
.java
Call toUniversalString method
•(1 of 2)
Call toString method
17
 2005 Pearson Education, Inc. All rights reserved.
18
19
20
// change time and output updated time
Call setTime
time.setTime( 13, 27, 6 );
System.out.print( "Universal time after setTime is: " );
21
System.out.println( time.toUniversalString() );
22
23
System.out.print( "Standard time after setTime is: " );
System.out.println( time.toString() );
24
25
System.out.println(); // output a blank line
26
// set time with invalid values; output updated time
27
time.setTime( 99, 99, 99 );
28
29
30
System.out.println( "After attempting invalid settings:" );
System.out.print( "Universal time: " );
System.out.println( time.toUniversalString() );
31
32
System.out.print( "Standard time: " );
System.out.println( time.toString() );
method
Outline
143
•Time1Test
.java
Call setTime method
with invalid values
•(2 of 2)
33
} // end main
34 } // end class Time1Test
The initial universal time is: 00:00:00
The initial standard time is: 12:00:00 AM
Universal time after setTime is: 13:27:06
Standard time after setTime is: 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM
 2005 Pearson Education, Inc. All rights reserved.
144
8.3 Controlling Access to Members
• A class’s public interface
– public methods a view of the services the class provides
to the class’s clients
• A class’s implementation details
– private variables and private methods are not
accessible to the class’s clients
 2005 Pearson Education, Inc. All rights reserved.
8.4 Referring to the Current Object’s
Members with the this Reference
145
• The this reference
– Any object can access a reference to itself with keyword
this
– Non-static methods implicitly use this when referring
to the object’s instance variables and other methods
– Can be used to access instance variables when they are
shadowed by local variables or method parameters
• A .java file can contain more than one class
– But only one class in each .java file can be public
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 8.4: ThisTest.java
// this used implicitly and explicitly to refer to members of an object.
3
4
5
6
public class ThisTest
{
public static void main( String args[] )
7
8
9
10
Create new SimpleTime object
•ThisTest.j
ava
{
SimpleTime time = new SimpleTime( 15, 30, 19 );
System.out.println( time.buildString() );
} // end main
11 } // end class ThisTest
12
13 // class SimpleTime demonstrates the "this" reference
14 class SimpleTime
15 {
16
17
18
private int hour;
// 0-23
private int minute; // 0-59
private int second; // 0-59
19
20
21
22
// if the constructor uses parameter names identical to
// instance variable names the "this" reference is
// required to distinguish between names
23
24
public SimpleTime( int hour, int minute, int second )
{
25
26
27
28
29
this.hour = hour;
this.minute = minute;
Outline
146
•(1 of 2)
Declare instance variables
Method parameters shadow
instance variables
// set "this" object's hour
// set "this" object's minute
this.second = second; // set "this" object's second
} // end SimpleTime constructor
Using this to access the object’s instance variables
 2005 Pearson Education, Inc. All rights reserved.
30
// use explicit and implicit "this" to call toUniversalString
31
public String buildString()
32
{
return String.format( "%24s: %s\n%24s: %s",
33
34
"this.toUniversalString()", this.toUniversalString(),
35
"toUniversalString()", toUniversalString() );
36
•ThisTest.j
ava
Using this explicitly and implicitly
to call toUniversalString
} // end method buildString
37
38
// convert to String in universal-time format (HH:MM:SS)
39
public String toUniversalString()
40
{
41
// "this" is not required here to access instance variables,
42
// because method does not have local variables with same
43
// names as instance variables
44
return String.format( "%02d:%02d:%02d",
45
46
Outline
147
•(2 of 2)
this.hour, this.minute, this.second );
} // end method toUniversalString
47 } // end class SimpleTime
Use of this not necessary here
this.toUniversalString(): 15:30:19
toUniversalString(): 15:30:19
 2005 Pearson Education, Inc. All rights reserved.
148
Common Programming Error 8.2
•It is often a logic error when a method contains
a parameter or local variable that has the same
name as a field of the class. In this case, use
reference this if you wish to access the field of
the class—otherwise, the method parameter or
local variable will be referenced.
 2005 Pearson Education, Inc. All rights reserved.
149
Error-Prevention Tip 8.1
•Avoid method parameter names or local variable
names that conflict with field names. This helps
prevent subtle, hard-to-locate bugs.
 2005 Pearson Education, Inc. All rights reserved.
150
Performance Tip 8.1
•Java conserves storage by maintaining only one
copy of each method per class—this method is
invoked by every object of the class. Each object,
on the other hand, has its own copy of the class’s
instance variables (i.e., non-static fields). Each
method of the class implicitly uses this to
determine the specific object of the class to
manipulate.
 2005 Pearson Education, Inc. All rights reserved.
151
8.5 Time Class Case Study: Overloaded
Constructors
• Overloaded constructors
– Provide multiple constructor definitions with different
signatures
• No-argument constructor
– A constructor invoked without arguments
• The this reference can be used to invoke
another constructor
– Allowed only as the first statement in a constructor’s body
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 8.5: Time2.java
// Time2 class declaration with overloaded constructors.
Outline
3
4
5
152
public class Time2
{
6
private int hour;
// 0 - 23
7
8
private int minute; // 0 - 59
private int second; // 0 - 59
9
10
11
12
// Time2 no-argument constructor: initializes each instance variable
// to zero; ensures that Time2 objects start in a consistent state
public Time2()
13
{
14
15
this( 0, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 no-argument constructor
16
17
18
19
20
21
// Time2 constructor: hour supplied, minute and second defaulted to 0
public Time2( int h )
Invoke three-argument
{
this( h, 0, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 one-argument constructor
22
23
// Time2 constructor: hour and minute supplied, second defaulted to 0
24
public Time2( int h, int m )
25
26
27
{
No-argument constructor
•Time2.jav
a
•(1 of 4)
constructor
this( h, m, 0 ); // invoke Time2 constructor with three arguments
} // end Time2 two-argument constructor
28
 2005 Pearson Education, Inc. All rights reserved.
29
// Time2 constructor: hour, minute and second supplied
30
public Time2( int h, int m, int s )
31
{
setTime( h, m, s ); // invoke setTime to validate time
32
33
Outline
Call setTime method
} // end Time2 three-argument constructor
34
35
// Time2 constructor: another Time2 object supplied
36
public Time2( Time2 time )
37
{
Constructor takes a reference to another
Time2 object as a parameter
constructor
38
// invoke Time2 three-argument
39
this( time.getHour(), time.getMinute(), time.getSecond() );
40
} // end Time2 constructor with a Time2 object argument
41
// Set Methods
43
// set a new time value using universal time; ensure that
44
// the data remains consistent by setting invalid values to zero
45
public void setTime( int h, int m, int s )
46
{
47
setHour( h );
48
setMinute( m ); // set the minute
49
setSecond( s ); // set the second
•Time2.jav
a
of 4) instance
Could have directly•(2
accessed
variables of object time here
42
50
153
// set the hour
} // end method setTime
51
 2005 Pearson Education, Inc. All rights reserved.
52
// validate and set hour
53
public void setHour( int h )
54
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
55
56
} // end method setHour
57
58
// validate and set minute
59
public void setMinute( int m )
60
{
} // end method setMinute
63
64
// validate and set second
65
public void setSecond( int s )
66
{
•(3 of 4)
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
67
68
•Time2.jav
a
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
61
62
Outline
154
} // end method setSecond
69
70
// Get Methods
71
// get hour value
72
public int getHour()
73
{
74
75
return hour;
} // end method getHour
76
 2005 Pearson Education, Inc. All rights reserved.
77
// get minute value
78
public int getMinute()
79
{
80
Outline
return minute;
81
} // end method getMinute
82
83
// get second value
84
85
86
public int getSecond()
{
return second;
87
} // end method getSecond
88
89
90
91
92
// convert to String in universal-time format (HH:MM:SS)
public String toUniversalString()
{
return String.format(
•Time2.jav
a
•(4 of 4)
93
94
95
"%02d:%02d:%02d", getHour(), getMinute(), getSecond() );
} // end method toUniversalString
96
97
98
// convert to String in standard-time format (H:MM:SS AM or PM)
public String toString()
{
99
100
101
155
return String.format( "%d:%02d:%02d %s",
( (getHour() == 0 || getHour() == 12) ? 12 : getHour() % 12 ),
getMinute(), getSecond(), ( getHour() < 12 ? "AM" : "PM" ) );
102
} // end method toString
103 } // end class Time2
 2005 Pearson Education, Inc. All rights reserved.
156
Common Programming Error 8.3
•It is a syntax error when this is used in a
constructor’s body to call another constructor of
the same class if that call is not the first
statement in the constructor. It is also a syntax
error when a method attempts to invoke a
constructor directly via this.
 2005 Pearson Education, Inc. All rights reserved.
157
Common Programming Error 8.4
•A constructor can call methods of the class. Be
aware that the instance variables might not yet
be in a consistent state, because the constructor
is in the process of initializing the object. Using
instance variables before they have been
initialized properly is a logic error.
 2005 Pearson Education, Inc. All rights reserved.
158
Software Engineering Observation 8.4
•When one object of a class has a reference to
another object of the same class, the first object
can access all the second object’s data and
methods (including those that are private).
 2005 Pearson Education, Inc. All rights reserved.
159
8.5 Time Class Case Study: Overloaded
Constructors (Cont.)
• Using set methods
– Having constructors use set methods to modify instance
variables instead of modifying them directly simplifies
implementation changing
 2005 Pearson Education, Inc. All rights reserved.
160
Software Engineering Observation 8.5
•When implementing a method of a class, use the
class’s set and get methods to access the class’s
private data. This simplifies code maintenance
and reduces the likelihood of errors.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.6: Time2Test.java
2
// Overloaded constructors used to initialize Time2 objects.
3
4
public class Time2Test
5
{
Outline
161
Call overloaded constructors
6
public static void main( String args[] )
7
{
8
Time2 t1 = new Time2();
// 00:00:00
9
Time2 t2 = new Time2( 2 );
// 02:00:00
10
Time2 t3 = new Time2( 21, 34 );
// 21:34:00
11
Time2 t4 = new Time2( 12, 25, 42 ); // 12:25:42
12
Time2 t5 = new Time2( 27, 74, 99 ); // 00:00:00
13
Time2 t6 = new Time2( t4 );
// 12:25:42
•Time2Test
.java
•(1 of 3)
14
15
System.out.println( "Constructed with:" );
16
System.out.println( "t1: all arguments defaulted" );
17
System.out.printf( "
%s\n", t1.toUniversalString() );
18
System.out.printf( "
%s\n", t1.toString() );
19
 2005 Pearson Education, Inc. All rights reserved.
20
21
System.out.println(
Outline
"t2: hour specified; minute and second defaulted" );
22
System.out.printf( "
%s\n", t2.toUniversalString() );
23
System.out.printf( "
%s\n", t2.toString() );
162
24
25
26
System.out.println(
•Time2Test
.java
"t3: hour and minute specified; second defaulted" );
27
System.out.printf( "
%s\n", t3.toUniversalString() );
28
System.out.printf( "
%s\n", t3.toString() );
29
30
System.out.println( "t4: hour, minute and second specified" );
31
System.out.printf( "
%s\n", t4.toUniversalString() );
32
System.out.printf( "
%s\n", t4.toString() );
•(2 of 3)
33
34
System.out.println( "t5: all invalid values specified" );
35
System.out.printf( "
%s\n", t5.toUniversalString() );
36
System.out.printf( "
%s\n", t5.toString() );
37
 2005 Pearson Education, Inc. All rights reserved.
38
System.out.println( "t6: Time2 object t4 specified" );
39
System.out.printf( "
%s\n", t6.toUniversalString() );
40
System.out.printf( "
%s\n", t6.toString() );
41
Outline
163
} // end main
42 } // end class Time2Test
t1: all arguments defaulted
00:00:00
12:00:00 AM
t2: hour specified; minute and second defaulted
02:00:00
2:00:00 AM
t3: hour and minute specified; second defaulted
21:34:00
9:34:00 PM
t4: hour, minute and second specified
12:25:42
12:25:42 PM
t5: all invalid values specified
00:00:00
12:00:00 AM
t6: Time2 object t4 specified
12:25:42
12:25:42 PM
•Time2Test
.java
•(3 of 3)
 2005 Pearson Education, Inc. All rights reserved.
164
8.6 Default and No-Argument
Constructors
• Every class must have at least one constructor
– If no constructors are declared, the compiler will create a
default constructor
• Takes no arguments and initializes instance variables to their
initial values specified in their declaration or to their default
values
– Default values are zero for primitive numeric types,
false for boolean values and null for references
– If constructors are declared, the default initialization for
objects of the class will be performed by a no-argument
constructor (if one is declared)
 2005 Pearson Education, Inc. All rights reserved.
165
Common Programming Error 8.5
If a class has constructors, but none of the public
constructors are no-argument constructors, and a
program attempts to call a no-argument
constructor to initialize an object of the class, a
compilation error occurs. A constructor can be
called with no arguments only if the class does not
have any constructors (in which case the default
constructor is called) or if the class has a public
no-argument constructor.
•5
 2005 Pearson Education, Inc. All rights reserved.
166
Software Engineering Observation 8.6
Java allows other methods of the class besides its
constructors to have the same name as the class
and to specify return types. Such methods are not
constructors and will not be called when an object
of the class is instantiated. Java determines which
methods are constructors by locating the methods
that have the same name as the class and do not
specify a return type.
•6
 2005 Pearson Education, Inc. All rights reserved.
167
8.7 Notes on Set and Get Methods
• Set methods
– Also known as mutator methods
– Assign values to instance variables
– Should validate new values for instance variables
• Can return a value to indicate invalid data
• Get methods
– Also known as accessor methods or query methods
– Obtain the values of instance variables
– Can control the format of the data it returns
 2005 Pearson Education, Inc. All rights reserved.
168
Software Engineering Observation 8.7
•When necessary, provide public methods to
change and retrieve the values of private
instance variables. This architecture helps hide
the implementation of a class from its clients,
which improves program modifiability.
 2005 Pearson Education, Inc. All rights reserved.
169
Software Engineering Observation 8.8
•Class designers need not provide set or get
methods for each private field. These capabilities
should be provided only when it makes sense.
 2005 Pearson Education, Inc. All rights reserved.
170
8.7 Notes on Set and Get Methods
(Cont.)
• Predicate methods
– Test whether a certain condition on the object is true or
false and returns the result
– Example: an isEmpty method for a container class (a
class capable of holding many objects)
• Encapsulating specific tasks into their own
methods simplifies debugging efforts
 2005 Pearson Education, Inc. All rights reserved.
171
8.8 Composition
• Composition
– A class can have references to objects of other classes as
members
– Sometimes referred to as a has-a relationship
 2005 Pearson Education, Inc. All rights reserved.
172
Software Engineering Observation 8.9
•One form of software reuse is composition, in
which a class has as members references to
objects of other classes.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.7: Date.java
2
// Date class declaration.
Outline
3
4
public class Date
5
{
6
private int month; // 1-12
7
private int day;
// 1-31 based on month
8
private int year;
// any year
173
•Date.java
9
10
// constructor: call checkMonth to confirm proper value for month;
11
// call checkDay to confirm proper value for day
12
public Date( int theMonth, int theDay, int theYear )
13
{
14
month = checkMonth( theMonth ); // validate month
15
year = theYear; // could validate year
16
day = checkDay( theDay ); // validate day
•(1 of 3)
17
18
19
20
21
System.out.printf(
"Date object constructor for date %s\n", this );
} // end Date constructor
 2005 Pearson Education, Inc. All rights reserved.
22
// utility method to confirm proper month value
23
private int checkMonth( int testMonth )
24
{
Outline
if ( testMonth > 0 && testMonth <= 12 ) // validate month
25
return testMonth;
26
27
else // month is invalid
28
{
•Date.java
System.out.printf(
29
"Invalid month (%d) set to 1.", testMonth );
30
return 1; // maintain object in consistent state
31
•(2 of 3)
} // end else
32
33
Validates month value
174
} // end method checkMonth
34
35
// utility method to confirm proper day value based on month and year
36
private int checkDay( int testDay )
37
{
38
39
Validates day value
int daysPerMonth[] =
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
40
 2005 Pearson Education, Inc. All rights reserved.
41
// check if day in range for month
42
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
Outline
return testDay;
43
175
44
45
// check for leap year
46
if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
47
return testDay;
48
49
50
System.out.printf( "Invalid day (%d) set to 1.", testDay );
51
return 1;
52
•Date.java
Check if the day is
February 29 on a
leap year
•(3 of 3)
// maintain object in consistent state
} // end method checkDay
53
54
// return a String of the form month/day/year
55
public String toString()
56
{
57
58
return String.format( "%d/%d/%d", month, day, year );
} // end method toString
59 } // end class Date
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.8: Employee.java
2
// Employee class with references to other objects.
Outline
3
4
public class Employee
5
{
6
private String firstName;
7
private String lastName;
8
private Date birthDate;
9
private Date hireDate;
Employee contains references
to two Date objects
176
•Employee.
java
10
11
// constructor to initialize name, birth date and hire date
12
public Employee( String first, String last, Date dateOfBirth,
Date dateOfHire )
13
14
{
15
firstName = first;
16
lastName = last;
17
birthDate = dateOfBirth;
18
hireDate = dateOfHire;
19
} // end Employee constructor
20
21
// convert Employee to String format
22
public String toString()
23
{
24
25
26
return String.format( "%s, %s
Hired: %s
Birthday: %s",
lastName, firstName, hireDate, birthDate );
} // end method toString
27 } // end class Employee
Implicit calls to hireDate and
birthDate’s toString methods
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.9: EmployeeTest.java
2
// Composition demonstration.
Outline
3
4
public class EmployeeTest
5
{
6
public static void main( String args[] )
7
{
Create an Employee object
8
Date birth = new Date( 7, 24, 1949 );
9
Date hire = new Date( 3, 12, 1988 );
10
Employee employee = new Employee( "Bob", "Blue", birth, hire );
177
•Employee
Test.java
11
12
13
System.out.println( employee );
} // end main
Display the Employee object
14 } // end class EmployeeTest
Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Blue, Bob Hired: 3/12/1988 Birthday: 7/24/1949
 2005 Pearson Education, Inc. All rights reserved.
178
8.10 Garbage Collection and Method
finalize
• Garbage collection
– JVM marks an object for garbage collection when there
are no more references to that object
– JVM’s garbage collector will retrieve those objects
memory so it can be used for other objects
•finalize method
– All classes in Java have the finalize method
• Inherited from the Object class
– finalize is called by the garbage collector when it
performs termination housekeeping
– finalize takes no parameters and has return type void
 2005 Pearson Education, Inc. All rights reserved.
179
Software Engineering Observation 8.10
•A class that uses system resources, such as files
on disk, should provide a method to eventually
release the resources. Many Java API classes
provide close or dispose methods for this
purpose. For example, class Scanner
(java.sun.com/j2se/5.0/docs/api/java/util
/Scanner.html) has a close method.
 2005 Pearson Education, Inc. All rights reserved.
180
8.11 static Class Members
•static fields
– Also known as class variables
– Represents class-wide information
– Used when:
• all objects of the class should share the same copy of this
instance variable or
• this instance variable should be accessible even when no
objects of the class exist
– Can be accessed with the class name or an object name and
a dot (.)
– Must be initialized in their declarations, or else the
compiler will initialize it with a default value (0 for ints)
 2005 Pearson Education, Inc. All rights reserved.
181
Software Engineering Observation 8.11
•Use a static variable when all objects of a class
must use the same copy of the variable.
 2005 Pearson Education, Inc. All rights reserved.
182
Software Engineering Observation 8.12
•Static class variables and methods exist, and can
be used, even if no objects of that class have been
instantiated.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.12: Employee.java
2
// Static variable used to maintain a count of the number of
3
// Employee objects in memory.
Outline
183
4
5
public class Employee
6
{
Declare a static field
7
private String firstName;
8
private String lastName;
9
private static int count = 0; // number of objects in memory
•Employee.
java
10
11
// initialize employee, add 1 to static count and
12
// output String indicating that constructor was called
13
public Employee( String first, String last )
14
{
•(1 of 2)
Increment static field
15
firstName = first;
16
lastName = last;
17
18
count++;
19
System.out.printf( "Employee constructor: %s %s; count = %d\n",
20
21
22
// increment static count of employees
firstName, lastName, count );
} // end Employee constructor
 2005 Pearson Education, Inc. All rights reserved.
23
24
// subtract 1 from static count when garbage
// collector calls finalize to clean up object;
25
// confirm that finalize was called
26
27
protected void finalize()
{
Declare method finalize
count--; // decrement static count of employees
System.out.printf( "Employee finalizer: %s %s; count = %d\n",
firstName, lastName, count );
28
29
30
31
Outline
} // end method finalize
32
33
34
// get first name
public String getFirstName()
35
{
36
37
38
39
40
41
42
43
44
45
return firstName;
} // end method getFirstName
46
public static int getCount()
184
•Employee.
java
•(2 of 2)
// get last name
public String getLastName()
{
return lastName;
} // end method getLastName
// static method to get static count value
47
{
48
return count;
49
} // end method getCount
50 } // end class Employee
Declare static method getCount to
get static field count
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.13: EmployeeTest.java
2
// Static member demonstration.
Outline
3
4
public class EmployeeTest
5
{
6
public static void main( String args[] )
7
{
8
// show that count is 0 before creating Employees
9
System.out.printf( "Employees before instantiation: %d\n",
10
11
Employee.getCount() );
185
•Employee
Test.java
Call static method getCount using class name Employee
12
// create two Employees; count should be 2
13
Employee e1 = new Employee( "Susan", "Baker" );
14
Employee e2 = new Employee( "Bob", "Blue" );
•(1 of 3)
15
Create new Employee objects
 2005 Pearson Education, Inc. All rights reserved.
16
// show that count is 2 after creating two Employees
17
System.out.println( "\nEmployees after instantiation: " );
18
System.out.printf( "via e1.getCount(): %d\n", e1.getCount() );
19
System.out.printf( "via e2.getCount(): %d\n", e2.getCount() );
20
System.out.printf( "via Employee.getCount(): %d\n",
21
Employee.getCount() );
22
Call static method
getCount outside objects
// get names of Employees
24
System.out.printf( "\nEmployee 1: %s %s\nEmployee 2: %s %s\n\n",
e1.getFirstName(), e1.getLastName(),
26
e2.getFirstName(), e2.getLastName() );
•Employee
Test.java
Call static method getCount
inside objects
23
25
Outline
186
•(2 of 3)
27
28
// in this example, there is only one reference to each Employee,
29
// so the following two statements cause the JVM to mark each
30
// Employee object for garbage collection
31
e1 = null;
32
e2 = null;
Remove references to objects, JVM will
mark them for garbage collection
33
34
35
System.gc(); // ask for garbage collection to occur now
Call static method gc of class System to indicate
that garbage collection should be attempted
 2005 Pearson Education, Inc. All rights reserved.
36
// show Employee count after calling garbage collector; count
37
// displayed may be 0, 1 or 2 based on whether garbage collector
38
// executes immediately and number of Employee objects collected
39
System.out.printf( "\nEmployees after System.gc(): %d\n",
40
41
Employee.getCount() );
} // end main
Call static method getCount
42 } // end class EmployeeTest
Outline
187
•Employee
Test.java
Employees before instantiation: 0
Employee constructor: Susan Baker; count = 1
Employee constructor: Bob Blue; count = 2
Employees after instantiation:
via e1.getCount(): 2
via e2.getCount(): 2
via Employee.getCount(): 2
•(3 of 3)
Employee 1: Susan Baker
Employee 2: Bob Blue
Employee finalizer: Bob Blue; count = 1
Employee finalizer: Susan Baker; count = 0
Employees after System.gc(): 0
 2005 Pearson Education, Inc. All rights reserved.
188
Good Programming Practice 8.1
•Invoke every static method by using the class
name and a dot (.) to emphasize that the method
being called is a static method.
 2005 Pearson Education, Inc. All rights reserved.
189
8.11 static Class Members (Cont.)
•String objects are immutable
– String concatenation operations actually result in the
creation of a new String object
•static method gc of class System
– Indicates that the garbage collector should make a besteffort attempt to reclaim objects eligible for garbage
collection
– It is possible that no objects or only a subset of eligible
objects will be collected
•static methods cannot access non-static
class members
– Also cannot use the this reference
 2005 Pearson Education, Inc. All rights reserved.
190
Common Programming Error 8.7
•A compilation error occurs if a static method
calls an instance (non-static) method in the same
class by using only the method name. Similarly, a
compilation error occurs if a static method
attempts to access an instance variable in the
same class by using only the variable name.
 2005 Pearson Education, Inc. All rights reserved.
191
Common Programming Error 8.8
•Referring to this in a static method is a
syntax error.
 2005 Pearson Education, Inc. All rights reserved.
192
8.12 static Import
•static import declarations
– Enables programmers to refer to imported static
members as if they were declared in the class that uses
them
– Single static import
• import static
packageName.ClassName.staticMemberName;
– static import on demand
• import static packageName.ClassName.*;
• Imports all static members of the specified class
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.14: StaticImportTest.java
2
// Using static import to import static methods of class Math.
3
import static java.lang.Math.*;
Outline
193
static import on demand
4
5
public class StaticImportTest
6
{
7
public static void main( String args[] )
8
{
•StaticImp
ortTest
9
System.out.printf( "sqrt( 900.0 ) = %.1f\n", sqrt( 900.0 ) );
10
System.out.printf( "ceil( -9.8 ) = %.1f\n", ceil( -9.8 ) );
11
System.out.printf( "log( E ) = %.1f\n", log( E ) );
12
System.out.printf( "cos( 0.0 ) = %.1f\n", cos( 0.0 ) );
13
•.java
} // end main
14 } // end class StaticImportTest
sqrt( 900.0 ) = 30.0
ceil( -9.8 ) = -9.0
log( E ) = 1.0
cos( 0.0 ) = 1.0
Use Math’s static methods and
instance variable without
preceding them with Math.
 2005 Pearson Education, Inc. All rights reserved.
194
Common Programming Error 8.9
•A compilation error occurs if a program
attempts to import static methods that have the
same signature or static fields that have the
same name from two or more classes.
 2005 Pearson Education, Inc. All rights reserved.
195
8.13 final Instance Variables
• Principle of least privilege
– Code should have only the privilege ad access it needs to
accomplish its task, but no more
•final instance variables
– Keyword final
• Specifies that a variable is not modifiable (is a constant)
– final instance variables can be initialized at their
declaration
• If they are not initialized in their declarations, they must be
initialized in all constructors
 2005 Pearson Education, Inc. All rights reserved.
196
Software Engineering Observation 8.13
•Declaring an instance variable as final helps
enforce the principle of least privilege. If an
instance variable should not be modified,
declare it to be final to prevent modification.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.15: Increment.java
2
// final instance variable in a class.
Outline
3
4
public class Increment
5
{
6
private int total = 0; // total of all increments
7
private final int INCREMENT; // constant variable (uninitialized)
8
9
// constructor initializes final instance variable INCREMENT
10
public Increment( int incrementValue )
11
{
instance variable
} // end Increment constructor
14
15
// add INCREMENT to total
16
public void addIncrementToTotal()
17
{
Initialize final instance variable
inside a constructor
total += INCREMENT;
18
19
•Increment.
java
Declare final
INCREMENT = incrementValue; // initialize constant variable (once)
12
13
197
} // end method addIncrementToTotal
20
21
// return String representation of an Increment object's data
22
public String toString()
23
{
24
25
return String.format( "total = %d", total );
} // end method toIncrementString
26 } // end class Increment
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.16: IncrementTest.java
2
// final variable initialized with a constructor argument.
Outline
3
4
public class IncrementTest
5
{
6
public static void main( String args[] )
7
{
8
•Increment
Test.java
Create an Increment object
Increment value = new Increment( 5 );
9
10
System.out.printf( "Before incrementing: %s\n\n", value );
11
12
for ( int i = 1; i <= 3; i++ )
13
{
Call method addIncrementToTotal
14
value.addIncrementToTotal();
15
System.out.printf( "After increment %d: %s\n", i, value );
16
17
198
} // end for
} // end main
18 } // end class IncrementTest
Before incrementing: total = 0
After increment 1: total = 5
After increment 2: total = 10
After increment 3: total = 15
 2005 Pearson Education, Inc. All rights reserved.
199
Common Programming Error 8.10
•Attempting to modify a final instance
variable after it is initialized is a compilation
error.
 2005 Pearson Education, Inc. All rights reserved.
200
Error-Prevention Tip 8.2
•Attempts to modify a final instance variable
are caught at compilation time rather than
causing execution-time errors. It is always
preferable to get bugs out at compilation time, if
possible, rather than allow them to slip through
to execution time (where studies have found that
the cost of repair is often many times more
expensive).
 2005 Pearson Education, Inc. All rights reserved.
201
Software Engineering Observation 8.14
•A final field should also be declared static if it
is initialized in its declaration. Once a final field
is initialized in its declaration, its value can never
change. Therefore, it is not necessary to have a
separate copy of the field for every object of the
class. Making the field static enables all objects
of the class to share the final field.
 2005 Pearson Education, Inc. All rights reserved.
202
Common Programming Error 8.11
•Not initializing a final instance variable in
its declaration or in every constructor of the
class yields a compilation error indicating
that the variable might not have been
initialized. The same error occurs if the class
initializes the variable in some, but not all, of
the class’s constructors.
 2005 Pearson Education, Inc. All rights reserved.
Increment.java:13: variable INCREMENT might not have been initialized
} // end Increment constructor
^
1 error
Outline
203
•Increment.
java
 2005 Pearson Education, Inc. All rights reserved.
204
8.14 Software Reusability
• Rapid application development
– Software reusability speeds the development of powerful,
high-quality software
• Java’s API
– provides an entire framework in which Java developers
can work to achieve true reusability and rapid application
development
– Documentation:
• java.sun.com/j2se/5.0/docs/api/index.html
• Or java.sun.com/j2se/5.0/download.html to download
 2005 Pearson Education, Inc. All rights reserved.
205
8.15 Data Abstraction and Encapsulation
• Data abstraction
– Information hiding
• Classes normally hide the details of their implementation
from their clients
– Abstract data types (ADTs)
• Data representation
– example: primitive type int is an abstract
representation of an integer
• ints are only approximations of integers, can
produce arithmetic overflow
• Operations that can be performed on data
 2005 Pearson Education, Inc. All rights reserved.
206
Good Programming Practice 8.2
•Avoid reinventing the wheel. Study the
capabilities of the Java API. If the API contains
a class that meets your program’s requirements,
use that class rather than create your own.
 2005 Pearson Education, Inc. All rights reserved.
207
8.15 Data Abstraction and Encapsulation
(Cont.)
• Queues
– Similar to a “waiting line”
• Clients place items in the queue (enqueue an item)
• Clients get items back from the queue (dequeue an item)
• First-in, first out (FIFO) order
– Internal data representation is hidden
• Clients only see the ability to enqueue and dequeue items
 2005 Pearson Education, Inc. All rights reserved.
208
Software Engineering Observation 8.15
Programmers create types through the class
mechanism. New types can be designed to be
convenient to use as the built-in types. This
marks Java as an extensible language. Although
the language is easy to extend via new types, the
programmer cannot alter the base language
itself.
•5
 2005 Pearson Education, Inc. All rights reserved.
209
8.16 Time Class Case Study: Creating
Packages
• To declare a reusable class
– Declare a public class
– Add a package declaration to the source-code file
• must be the very first executable statement in the file
• package name should consist of your Internet domain name
in reverse order followed by other names for the package
– example: com.deitel.jhtp6.ch08
– package name is part of the fully qualified class name
• Distinguishes between multiple classes with the same
name belonging to different packages
• Prevents name conflict (also called name collision)
– Class name without package name is the simple name
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.18: Time1.java
2
// Time1 class declaration maintains the time in 24-hour format.
3
package com.deitel.jhtp6.ch08;
4
Outline
210
package declaration
5
public class Time1
6
{
7
private int hour;
// 0 - 23
8
private int minute; // 0 - 59
9
private int second; // 0 - 59
Time1 is a public class so it can be
used by importers of this package
•Time1.jav
a
10
11
// set a new time value using universal time; perform
12
// validity checks on the data; set invalid values to zero
13
public void setTime( int h, int m, int s )
14
{
•(1 of 2)
15
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
16
minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); // validate minute
17
second = ( ( s >= 0 && s < 60 ) ? s : 0 ); // validate second
18
// validate hour
} // end method setTime
19
 2005 Pearson Education, Inc. All rights reserved.
20
// convert to String in universal-time format (HH:MM:SS)
21
public String toUniversalString()
22
{
return String.format( "%02d:%02d:%02d", hour, minute, second );
23
24
Outline
} // end method toUniversalString
25
26
// convert to String in standard-time format (H:MM:SS AM or PM)
27
public String toString()
28
{
29
•Time1.jav
a
return String.format( "%d:%02d:%02d %s",
30
( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
31
minute, second, ( hour < 12 ? "AM" : "PM" ) );
32
211
} // end method toString
•(2 of 2)
33 } // end class Time1
 2005 Pearson Education, Inc. All rights reserved.
212
8.16 Time Class Case Study: Creating
Packages (Cont.)
– Compile the class so that it is placed in the appropriate
package directory structure
• Example: our package should be in the directory
com
deitel
jhtp6
ch08
• javac command-line option –d
– javac creates appropriate directories based on the
class’s package declaration
– A period (.) after –d represents the current directory
 2005 Pearson Education, Inc. All rights reserved.
213
8.16 Time Class Case Study: Creating
Packages (Cont.)
– Import the reusable class into a program
• Single-type-import declaration
– Imports a single class
– Example: import java.util.Random;
• Type-import-on-demand declaration
– Imports all classes in a package
– Example: import java.util.*;
 2005 Pearson Education, Inc. All rights reserved.
214
Common Programming Error 8.12
•Using the import declaration import java.*;
causes a compilation error. You must specify the
exact name of the package from which you want
to import classes.
 2005 Pearson Education, Inc. All rights reserved.
1
// Fig. 8.19: Time1PackageTest.java
2
// Time1 object used in an application.
3
import com.deitel.jhtp6.ch08.Time1; // import class Time1
Outline
215
4
5
public class Time1PackageTest
6
{
7
public static void main( String args[] )
8
{
Single-type import declaration
9
// create and initialize a Time1 object
10
Time1 time = new Time1(); // calls Time1 constructor
11
12
// output string representations of the time
13
System.out.print( "The initial universal time is: " );
14
System.out.println( time.toUniversalString() );
15
System.out.print( "The initial standard time is: " );
16
System.out.println( time.toString() );
17
System.out.println(); // output a blank line
•Time1Pac
kageTest
•.java
Refer to the Time1 class
by its simple name
• (1 of 2)
18
 2005 Pearson Education, Inc. All rights reserved.
19
// change time and output updated time
20
time.setTime( 13, 27, 6 );
21
System.out.print( "Universal time after setTime is: " );
22
System.out.println( time.toUniversalString() );
23
System.out.print( "Standard time after setTime is: " );
24
System.out.println( time.toString() );
25
System.out.println(); // output a blank line
•Time1Pac
kageTest
26
27
// set time with invalid values; output updated time
28
time.setTime( 99, 99, 99 );
29
System.out.println( "After attempting invalid settings:" );
30
System.out.print( "Universal time: " );
31
System.out.println( time.toUniversalString() );
32
System.out.print( "Standard time: " );
33
System.out.println( time.toString() );
34
Outline
216
•.java
• (2 of 2)
} // end main
35 } // end class Time1PackageTest
The initial universal time is: 00:00:00
The initial standard time is: 12:00:00 AM
Universal time after setTime is: 13:27:06
Standard time after setTime is: 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM
 2005 Pearson Education, Inc. All rights reserved.
217
8.16 Time Class Case Study: Creating
Packages (Cont.)
• Class loader
– Locates classes that the compiler needs
• First searches standard Java classes bundled with the JDK
• Then searches for optional packages
– These are enabled by Java’s extension mechanism
• Finally searches the classpath
– List of directories or archive files separated by directory
separators
• These files normally end with .jar or .zip
• Standard classes are in the archive file rt.jar
 2005 Pearson Education, Inc. All rights reserved.
218
8.16 Time Class Case Study: Creating
Packages (Cont.)
• To use a classpath other than the current
directory
– -classpath option for the javac compiler
– Set the CLASSPATH environment variable
• The JVM must locate classes just as the compiler
does
– The java command can use other classpathes by using the
same techniques that the javac command uses
 2005 Pearson Education, Inc. All rights reserved.
219
Common Programming Error 8.13
•Specifying an explicit classpath eliminates the
current directory from the classpath. This
prevents classes in the current directory
(including packages in the current directory) from
loading properly. If classes must be loaded from
the current directory, include a dot (.) in the
classpath to specify the current directory.
 2005 Pearson Education, Inc. All rights reserved.
220
Software Engineering Observation 8.16
•In general, it is a better practice to use the
-classpath option of the compiler, rather
than the CLASSPATH environment variable,
to specify the classpath for a program.
This enables each application to have its
own classpath.
 2005 Pearson Education, Inc. All rights reserved.
221
Error-Prevention Tip 8.3
•Specifying the classpath with the CLASSPATH
environment variable can cause subtle and
difficult-to-locate errors in programs that use
different versions of the same package.
 2005 Pearson Education, Inc. All rights reserved.
222
8.17 Package Access
• Package access
– Methods and variables declared without any access
modifier are given package access
– This has no effect if the program consists of one class
– This does have an effect if the program contains multiple
classes from the same package
• Package-access members can be directly accessed through
the appropriate references to objects in other classes
belonging to the same package
 2005 Pearson Education, Inc. All rights reserved.
1
2
// Fig. 8.20: PackageDataTest.java
// Package-access members of a class are accessible by other classes
3
// in the same package.
4
5
public class PackageDataTest
6
{
7
8
9
10
11
12
Outline
223
•PackageD
ataTest
public static void main( String args[] )
{
PackageData packageData = new PackageData();
// output String representation of packageData
System.out.printf( "After instantiation:\n%s\n", packageData );
•.java
13
14
15
16
// change package access data in packageData object
packageData.number = 77;
Can directly access
packageData.string = "Goodbye";
package-access members
• (1 of 2)
17
18
19
20
// output String representation of packageData
System.out.printf( "\nAfter changing values:\n%s\n", packageData );
} // end main
21 } // end class PackageDataTest
22
 2005 Pearson Education, Inc. All rights reserved.
23 // class with package access instance variables
Outline
24 class PackageData
25 {
26
int number; // package-access instance variable
27
String string; // package-access instance variable
28
29
// constructor
30
public PackageData()
31
{
32
number = 0;
33
string = "Hello";
34
Package-access instance variables
224
•PackageD
ataTest
•.java
} // end PackageData constructor
35
36
// return PackageData object String representation
37
public String toString()
38
{
39
40
• (2 of 2)
return String.format( "number: %d; string: %s", number, string );
} // end method toString
41 } // end class PackageData
After instantiation:
number: 0; string: Hello
After changing values:
number: 77; string: Goodbye
 2005 Pearson Education, Inc. All rights reserved.
225
8.19 Starting to Program the Classes of
the ATM System
• Visibility
– Attributes normally should be private, methods invoked by
clients should be public
– Visibility markers in UML
• A plus sign (+) indicates public visibility
• A minus sign (-) indicates private visibility
• Navigability
– Navigability arrows indicate in which direction an
association can be traversed
– Bidirectional navigability
• Associations with navigability arrows at both ends or no
navigability arrows at all can be traversed in either direction
 2005 Pearson Education, Inc. All rights reserved.