Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 1
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Chapter 7
Class Variables and Methods
Versus Instance Methods
• Review from Chapter 3:
– A Java program consists of classes.
– Most classes contain both instance variables and instance methods.
– Any object created from a class will have its own copy of the class’s instance variables, and that object will be capable of calling the class’s (public) instance methods.
• Examples of classes:
– Account
– String (part of the Java API)
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 3
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Instance Method Review
• An instance method may access the instance
variables in an object without changing them, or it may modify instance variables.
• If acct is an Account variable, the call
acct.deposit(1000.00);
deposits $1000 into the Account object that acct represents.
• If str contains a String object, the length method can be used to find the length of the string:
int len = str.length();
Class Methods
• Not all methods require access to instance variables.
• For example, a method that computes the square root of a number has nothing to do with objects.
• Methods that don’t need access to instance
variables are known as class methods (or static methods.)
• A class method—like all methods in Java—must
belong to a class.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 5
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Class Methods
• If a class method has been declared public, it can be called as follows:
class . method-name ( arguments )
• When a class method is called by another method
in the same class, the class name and dot can be
omitted.
Class Methods
• Class methods used in Chapter 2:
SimpleIO.prompt SimpleIO.readLine Convert.toDouble Integer.parseInt Math.abs
Math.max
Math.min
Math.pow
Math.round
Math.sqrt
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 7
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Class Methods
• Uses of class methods:
– To provide a service to other classes. Methods in this category are declared public.
– To help other methods in the same class. “Helper”
methods provide assistance to other methods in the same class. Helper methods should be private.
– To provide access to hidden class variables. If a class variable is private, the only way for a method in a
different class to access the variable or to change its value is to call a class method that has permission to access the variable. Methods in this category are
declared public.
Class Methods
• Class methods have another important purpose: to specify where a program begins execution.
• Every Java application must have a main method.
main is a class method, so every Java application has at least one class method.
• Many classes in the Java API provide class
methods, including Math, System, and
String.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 9
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: The Math Class
• The Math class contains no instance variables and no instance methods; it’s just a repository for math functions (class methods) and math constants.
• Since Math has no instance variables, so there’s no point in creating instances of this class.
• A class from which objects can be created is said to be instantiable. The Math class is not
instantiable.
Example: The System Class
• The System class contains a number of class
methods, including exit, which causes program termination.
• A call of System.exit:
System.exit(0);
• The argument (an int value) is a status code that can be tested after program termination.
• By convention, 0 indicates normal termination.
Any other value (such as –1) indicates abnormal
termination.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 11
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: The System Class
• Calling System.exit is a more drastic way to terminate a program than simply returning from main.
• If a program displays a frame on the screen, the program won’t terminate until the frame is closed, even if main has completed execution.
• On the other hand, calling System.exit causes immediate program termination; any frames that are visible on the screen will be closed.
• The System class is not instantiable.
Example: The String Class
• Java’s String class contains several overloaded class methods named valueOf that convert
different types of data to string form.
• Examples:
String intString = String.valueOf(607);
String doubleString = String.valueOf(4.5);
The value of intString will be "607" and the value of doubleString will be "4.5".
• String is an example of a class that contains
both instance methods and class methods.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 13
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Summary
Instance Methods
• Perform an operation on an object.
• Are called by an object.
• Have access to instance variables inside the calling object.
Class Methods
• Do not perform an
operation on an object.
• Are not called by an object.
• Do not have access to
instance variables.
7.2 Writing Class Methods
• Writing a class method is similar to writing an instance method, except that the declaration of a class method must contain the word static.
• Parts of a class method declaration:
– Access modifier – The word static – Result type
– Method name
– Parameters
– Body
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 15
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Declaring Class Methods
• Example of a class method declaration:
Parameters for Class Methods
• Java requires that main’s result type be void and that main have one parameter of type String[]
(array of String objects).
• Other class methods may have any number of parameters, including none.
• If a method has more than one parameter, each
parameter except the last must be followed by a
comma.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 17
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Access Modifiers for Class Methods
• Java requires that the main method be declared public. Other class methods can be declared either public or private.
• Class methods that are intended for use by other classes should be declared public.
• Class methods that are intended for use within a single class should be declared private.
• A private method can be modified without
having to worry about how the changes might
affect other classes.
Example: A Termination Method
• When a program encounters an error condition, it may need to notify the user and terminate.
• The following two statements accomplish this task:
System.out.println("Invalid input; consult manual.");
System.exit(-1); // Terminate abnormally
• Because these statements might appear many times in a program, with only minor changes
(different messages to the user), it makes sense to
put them into a class method.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 19
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: A Termination Method
• A declaration of the class method:
private static void terminate(String message) { System.out.println(message);
System.exit(-1); // Terminate abnormally }
• A call of terminate:
terminate("Invalid input; consult manual.");
Because this call will be in the same class as the
method itself, there’s no need to mention the class
name in the call.
Local Variables
• The body of any class or instance method may contain declarations of local variables.
• Properties of local variables:
– A local variable can be accessed only within the method that contains its declaration.
– When a method returns, its local variables no longer exist, so their values are lost.
– A method is not allowed to access the value stored in a local variable until the variable has been initialized.
– A local variable can be declared final to indicate that
its value doesn’t change after initialization.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 21
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
7.3 The return Statement
• When a method has a result type other than void, a return statement must be used to specify what value the method returns.
• Form of the return statement:
return expression ;
• The expression is often just a literal or a variable:
return 0;
return n;
• Expressions containing operators are also allowed:
return x * x - 2 * x + 1;
Using Variables in return Statements
• A class method that computes the value of the polynomial x
2– 2x + 1:
private static double poly(double x) { return x * x - 2 * x + 1;
}
• A local variable could be used to store the return value:
private static double poly(double x) { double y = x * x - 2 * x + 1;
return y;
}
• It’s usually best to avoid variables that are assigned a
value only once.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 23
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
A Common Error
• When a method returns a result, make sure that there’s no way to leave the method without
executing a return statement.
• The following method body is illegal, because the method returns nothing if n is equal to 0:
if (n > 0) return +1;
else if (n < 0)
return -1;
return Statements in void Methods
• return statements can be used in methods whose result type is void.
• The expression after the word return must be omitted:
return;
• A return statement of this form allows a
method to return before it has executed all the
statements in its body.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 25
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: A Dollar-Formatting Method
• In the U.S., monetary amounts are normally
displayed in the form dollars.cents, where cents is a two-digit number between 00 and 99.
• If a double variable is used to store a dollar amount, System.out.print and
System.out.println won’t always provide the desired formatting: 10.50 will display as 10.5 and 10000000.00 will be printed as 1.0E7.
• Also, amounts won’t be rounded to cents, so
values such as 10.50001 may be printed.
Example: A Dollar-Formatting Method
• The Java API provides methods for formatting numbers, but it’s easy to write such a method.
• A possible strategy for converting a dollar amount to a string that’s suitable for printing:
1. Multiply the amount by 100 and round to the nearest integer (call this roundedAmount).
2. Determine the number of dollars (roundedAmount divided by 100) and the number of cents (the remainder when
roundedAmount is divided by 100).
3. Build a string consisting of the number of dollars, a period, and the number of cents. If the number of cents is a single-digit number, put a zero between the period and the number of cents.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 27
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: A Dollar-Formatting Method
• A class method that implements this strategy:
private static String formatAsMoney(double amount) { long roundedAmount = Math.round(amount * 100);
long dollars = roundedAmount / 100;
long cents = roundedAmount % 100;
String result;
if (cents <= 9)
result = dollars + ".0" + cents;
else
result = dollars + "." + cents;
return result;
}
• Math.round returns a long value. long is
similar to int but allows numbers to be larger.
Example: A Dollar-Formatting Method
• formatAsMoney can be simplified by replacing the if statement and the return statement with the following statement:
if (cents <= 9)
return dollars + ".0" + cents;
else
return dollars + "." + cents;
• Once this change has been made, the declaration
of result can be removed.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 29
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Example: A Dollar-Formatting Method
• An example of calling formatAsMoney:
String formattedAmount =
formatAsMoney(dollarAmount);
dollarAmount is a double variable.
• The value returned by formatAsMoney can be used without first storing it in a variable:
System.out.println(
"$" + formatAsMoney(dollarAmount));
Conditional Expressions
• The two return statements in the
formatAsMoney method are nearly identical:
if (cents <= 9)
return dollars + ".0" + cents;
else
return dollars + "." + cents;
This suggests that there might be a way to simplify the code.
• Java’s conditional operator is often handy in such
situations.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 31
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Conditional Expressions
• The conditional operator is similar to the if
statement: it tests a condition and performs one of two actions, depending on the outcome of the test.
• Unlike the if statement, the conditional operator produces a value.
• This property gives the conditional operator
greater flexibility than the if statement.
Conditional Expressions
• The conditional operator consists of the symbols ? and :, which must be used together:
expr1 ? expr2 : expr3
expr1 must be a boolean expression; expr2 and expr3 are normally expressions of the same type.
• The resulting expression is said to be a conditional expression.
• The conditional operator is a ternary operator,
because it requires three operands instead of one
or two.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 33
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Conditional Expressions
• The conditional expression expr1 ? expr2 : expr3 should be read “if expr1 then expr2 else expr3.”
• A conditional expression is evaluated in stages:
– expr1 is evaluated first.
– If the value of expr1 is true, then expr2 is evaluated, and its value is the value of the entire conditional.
– If the value of expr1 is false, then the value of expr3 is
the value of the entire conditional.
Conditional Expressions
• The if statement in the formatAsMoney
method can be replaced by a return statement:
return (cents <= 9) ? (dollars + ".0" + cents) : (dollars + "." + cents);
• The return statement can be condensed further:
return dollars + (cents <= 9 ? ".0" : ".") + cents;
• The parentheses in the second example are
mandatory. The conditional operator has lower
precedence than all other operators except the
assignment operators.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 35
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Conditional Expressions
• The conditional operator isn’t used much in Java except in return statements.
• Conditional expressions occasionally appear in calls of System.out.print or System.out.println.
• The statement
if (isLeapYear)
System.out.println("February has 29 days");
else
System.out.println("February has 28 days");
could be written as
System.out.println("February has " +
(isLeapYear ? 29 : 28) + " days");
Conditional Expressions
• A conditional expression can be used just like any other kind of expression.
• For example, a conditional expression can appear on the right side of an assignment:
int i = 1;
int j = 2;
int m = i > j ? i : j; // m is 2 int n = (i >= 0 ? i : 0) + j; // n is 3
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 37
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
7.4 Parameters
• A method is allowed to have parameters, which represent values that will be supplied when the method is called.
• The values actually supplied to the method at the time of the call are said to be arguments.
• The issues that arise when parameters are used are relevant to both instance methods and class
methods.
How Arguments Are Passed
• When a method is called, it is supplied with copies of the arguments that appear in the method call.
• The arguments are passed by value, because the value of each argument is given to the called method.
• The meaning of “copy” depends on the type of the argument.
• An object variable contains a reference to an object, not the object itself.
• For this reason, classes are said to be reference types.
(Array types are also reference types.)
• All other types are said to be primitive types.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 39
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• The effect of passing an argument to a method:
– Primitive type. The value of the argument is copied into the corresponding parameter.
– Reference type. The value of the argument—a reference
—is copied into the parameter.
• Assigning a new value to a parameter is legal but has no effect on the corresponding argument.
• If the parameter refers to an object, then changes made to that object—for example, by calling a
method that modifies the object—will be reflected
in the argument.
How Arguments Are Passed
• Example 1: Assigning a new value to a parameter.
• The following class method writes a line consisting of stars (asterisks):
private static void printStars(int numStars) { while (numStars-- > 0)
System.out.print('*');
System.out.println();
}
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 41
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• An example in which printStars is called:
int n = 30;
System.out.println("Value of n before call: " + n);
printStars(n);
System.out.println("Value of n after call: " + n);
• The output produced by these statements:
Value of n before call: 30
******************************
Value of n after call: 30
How Arguments Are Passed
• When printStars was called, the value of n
was copied into the numStars parameter:
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 43
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• Because numStars was a copy of n,
decrementing numStars didn’t change n.
• At the end of the method call, n and numStars
have the following appearance:
How Arguments Are Passed
• Example 2: Modifying an object passed as an argument.
• A method that transfers the balance in
oldAccount to newAccount, then closes oldAccount:
private static void transferBalance(
Account oldAccount, Account newAccount) { newAccount.deposit(oldAccount.getBalance());
oldAccount.close();
}
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 45
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• The calls of deposit and close don’t change the values of oldAccount and newAccount.
• They do, however, change the state of the objects that oldAccount and newAccount represent.
• To see how transferBalance works, assume that acct1 and acct2 are declared as follows:
Account acct1 = new Account(1000.00);
Account acct2 = new Account(500.00);
How Arguments Are Passed
• A visual representation of acct1 and acct2:
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 47
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• Now suppose that the following statement is executed:
transferBalance(acct1, acct2);
• As the method begins to execute, acct1 is copied into oldAccount, and acct2 is copied into
newAccount.
How Arguments Are Passed
• oldAccount now refers to the same object as acct1,
and newAccount refers to the same object as acct2:
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 49
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
How Arguments Are Passed
• The transferBalance method executes the call oldAccount.getBalance(), which returns 1000.00.
• Next, this value is added to the balance stored in the newAccount object, causing its balance to increase to 1500.00.
• Finally, oldAccount.close() is executed,
causing the balance in the oldAccount object to
be set to zero.
How Arguments Are Passed
• As a result of calling transferBalance, the
state of the acct1 and acct2 objects is changed:
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 51
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Array Parameters
• Passing arrays to methods is much like passing objects.
• A method that searches an array of strings to see if it contains a particular string (the search key):
private static int findString(String[] strings, String key) {
for (int i = 0; i < strings.length; i++) if (strings[i].equals(key))
return i;
return -1;
}
• If it finds the key in the array, findString returns the
key’s position. If findString fails to find the key, it
returns –1.
Array Parameters
• When an array is passed to a method, only a reference to the array is copied.
• As a result, passing an array to a method takes very little time.
• Also, a method can modify the elements of any array passed to it.
• For example, the following method will assign zero to the elements of an array passed to it:
private static void setElementsToZero(int[] a) { for (int i = 0; i < a.length; i++)
a[i] = 0;
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 53
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Program Arguments
• In many operating systems, the user can launch programs from a command line.
• The Java compiler itself is launched from the command line:
javac MyProgram.java
• javac obtains the name of the .java file from the command line.
• When a program is launched from the command
line, it can access information (file names, for
example) entered as part of the command.
Program Arguments
• Some programs have switches or options that can be specified on the command line to affect the
program’s behavior.
• These usually begin with a distinctive character, such as - or /.
• javac has a -O option, which causes it to
“optimize” a program for better performance:
javac -O MyProgram.java
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 55
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Program Arguments
• The term program arguments (or command-line arguments) refers to any data supplied by the user on the command line (not including the name of the program itself).
• Command-line arguments don’t have to be options or file names, although in practice they usually
are.
Program Arguments
• It’s easy to write a program that accesses
command-line arguments supplied by the user.
• The main method is required to have a single parameter, which is customarily named args:
public static void main(String[] args) { …
}
• When the program is executed, args will contain
the program’s command-line arguments.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 57
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Program Arguments
• Suppose that CopyFile is a Java program that’s been launched using the following command:
java CopyFile MyProgram.java MyProgram2.java
• Inside CopyFile’s main method, the args array will contain the following values:
args[0] "MyProgram.java"
args[1] "MyProgram2.java"
Program Arguments
• The main method’s parameter doesn’t have to be named args ( “arguments”). argv—“argument vector”—is also popular.
• The square brackets can go after args if desired:
public static void main(String args[]) { …
}
• Typically, a program will use a loop to examine
and process the command-line arguments.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 59
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Program: Printing Command-Line Arguments
• A program that prints each command-line argument on a line by itself:
PrintArgs.java
// Prints command-line arguments on separate lines public class PrintArgs {
public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]);
} }
Program: Printing Command-Line Arguments
• Suppose that PrintArgs is executed using the following command:
java PrintArgs Java rules
• The output of PrintArgs:
Java
rules
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 61
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
7.5 Class Variables
• Objects store their state in instance variables.
Every object has its own set of these variables.
• Variables that belong to a class, but not to any particular instance of a class, are called class variables.
• Some books use the terms static variables or static fields instead.
• Class variables are stored only once in the entire
program.
Declaring Class Variables
• In declarations of class variables, the word
static is inserted between the access modifier and the type of the variable:
public static int numAccounts;
private static int windowHeight;
• Variables that are declared public are accessible outside the class.
• Variables that are declared private are hidden
inside the class.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 63
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Using Class Variables
• A public class variable can be accessed by writing the name of the class, a dot, and the name of the variable.
• If the numAccounts is declared in a class named Account, the following statement is legal:
int accountsOpen = Account.numAccounts;
• Within the class in which it’s declared, a class variable can be accessed directly, without a class name or dot:
numAccounts++;
• A private class variable can be accessed only within its own class, so the class name and dot aren’t needed:
windowHeight = 200;
Uses for Class Variables
• Common uses for class variables:
– As global variables. (A global variable is a variable that can be used by any method in any class.)
– As constants.
– To store data for class methods.
• Class variables can also be used by instance
methods.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 65
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
as Global Variables
• In Java, there’s no way to declare a variable that exists “outside” the classes in a program.
• Instead, a variable that must be universally
available is put into a class and declared to be a public class variable.
• Global variables make programs harder to test and harder to modify, so it’s usually best to avoid
them.
Class Variables in the System Class
• Every call of System.out.print or
System.out.println involves a global variable.
• The System class has three class variables: in, out, and err.
• These variables are all public, which means that they can be accessed by writing System.in, System.out, and System.err.
• Each variable represents a stream—a source of
input or a destination for output.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 67
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Class Variables in the System Class
• System.in represents the standard input stream.
By default, the standard input stream is attached to the user’s keyboard.
• System.out represents the standard output stream.
By default, data written to System.out is displayed in the window in the program was launched.
• System.err represents the standard error stream, which is a convenient place to write error messages.
By default, data written to System.err is displayed
in the same window as data written to System.out.
Redirecting the Standard Streams
• Operating systems often allow the user to redirect the standard streams.
• In Windows or Unix, the standard input stream can be redirected so that data comes from a file instead of from the keyboard:
java MyProgram <myInputFile
• The output of a program can also be sent to a file:
java MyProgram >myOutputFile
myOutputFile will be created if it doesn’t exist.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 69
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Redirecting the Standard Streams
• A program can read from one file and write to another:
java MyProgram <myInputFile >myOutputFile
• If the user redirects the program’s output, error
messages written to System.out won’t appear on the screen.
• Error messages written to System.err will still appear on the screen, because redirecting
System.out has no effect on System.err.
• Writing to System.err is similar to writing to System.out:
System.err.println("Invalid data encountered");
The PrintStream Class
• System.out and System.err are instances of the PrintStream class, which provides the print and println methods.
• Consider a typical call of System.out.println:
System.out.println("Java rules!");
• System.out is a class variable that represents an instance of the PrintStream class.
• This object is invoking println, one of the instance
methods in the PrintStream class.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 71
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Using Class Variables as Constants
• Including the word final in the declaration of a class variable makes it a constant.
• Java’s Math class contains two final class variables:
public class Math {
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
…}
• E and PI are accessed by writing Math.E and
Math.PI.
Using Class Variables as Constants
• Other examples of class variables used as constants:
– Color.white, Color.black, ...
– Font.PLAIN, Font.BOLD, Font.ITALIC
• Most API classes follow the convention of using all uppercase letters for names of constants.
• Like all class variables, constants can be declared public or private.
• Constants that are to be used by other classes must
be declared public.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 73
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Store Data for Class Methods
• When a method returns, its local variables no longer exist.
• If a class method needs to store data where it will be safe after the method returns, it must use a class variable instead of a local variable.
• Class variables are also used for sharing data among class methods in a class.
• Class variables that store data for class methods
should be declared private.
Summary
Instance Variables
• Declared in a class.
• Created when an instance of the class is created.
• Retain values as long as object exists.
• Access
controlled by public and
Class Variables
• Declared in a class.
• Created when program begins to execute.
• Retain values until program terminates.
• Access
controlled by public and
Local Variables
• Declared in a method.
• Created when method is called.
• Retain values until method returns.
• Access limited to
method in which
declared.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 75
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
and Methods to a Class
• The outline of a program that contains class
variables and class methods, in addition to main:
public class class-name { declarations of class variables
public static void main(String[] args) { …
}
declarations of class methods }
• Java doesn’t require that class variables and
methods go in any particular order.
DisplayText Program
• The DisplayText program could benefit from the addition of class variables and methods.
• The original program:
// Displays text in three different colors and styles import java.awt.*;
import jpb.*;
public class DisplayText {
public static void main(String[] args) { // Create drawable frame
DrawableFrame df = new DrawableFrame("Display Text");
df.show();
df.setSize(210, 85);
// Obtain graphics context
Graphics g = df.getGraphicsContext();
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 77
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
DisplayText Program
// Display "Monospaced Bold"
g.setColor(Color.red);
g.setFont(new Font("Monospaced", Font.BOLD, 20));
g.drawString("Monospaced Bold", 15, 25);
// Display "SansSerif Italic"
g.setColor(Color.green);
g.setFont(new Font("SansSerif", Font.ITALIC, 20));
g.drawString("SansSerif Italic", 15, 50);
// Display "Serif Plain"
g.setColor(Color.blue);
g.setFont(new Font("Serif", Font.PLAIN, 20));
g.drawString("Serif Plain", 15, 75);
// Repaint frame df.repaint();
}}
DisplayText Program
• A method named displayFont could perform the setColor/setFont/drawString steps.
• The differences in the steps are the drawing color, the font name and style, the string to be displayed, and the y coordinate of the string’s baseline. These will need to be parameters to displayFont.
• The steps don’t change any of the program’s
variables, so displayFont won’t need to return
a result.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 79
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
DisplayText Program
• The displayFont method:
private static void displayFont(Color c, String fontName, int fontStyle,
String message, int y) { g.setColor(c);
g.setFont(new Font(fontName, fontStyle, 20));
g.drawString(message, 15, y);
}
• There’s one problem: displayFont uses the variable g, which is declared in main.
• Either displayFont will need a Graphics
parameter, or g will need to be a class variable.
// Displays text in three different colors and styles import java.awt.*;
import jpb.*;
public class DisplayText2 {
private static Graphics g; // Class variable public static void main(String[] args) {
// Create drawable frame
DrawableFrame df = new DrawableFrame("Display Text");
df.show();
df.setSize(210, 85);
// Obtain graphics context g = df.getGraphicsContext();
// Display "Monospaced Bold"
displayFont(Color.red, "Monospaced", Font.BOLD,
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 81
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
displayFont(Color.green, "SansSerif", Font.ITALIC, "SansSerif Italic", 50);
// Display "Serif Plain"
displayFont(Color.blue, "Serif", Font.PLAIN, "Serif Plain", 75);
// Repaint frame df.repaint();
}
private static void displayFont(Color c, String fontName, int fontStyle,
String message, int y) { g.setColor(c);
g.setFont(new Font(fontName, fontStyle, 20));
g.drawString(message, 15, y);
} }
7.7 Writing Helper Methods
• Instead of putting all the code for a program into main, it’s better to delegate some of its duties to helper methods.
• In general, a helper method is any method whose job is to assist another method, not necessarily main.
• A helper for a class method such as main must be another class method, because class methods aren't allowed to call instance methods in the same class.
• Instance methods can have helpers as well. A helper for an instance method can be either an instance
method or a class method.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 83
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Advantages of Using Helper Methods
• Helper methods have two primary advantages:
– Greater clarity. The main method can be shortened, with helper methods taking care of details.
– Less redundancy. A repeated segment of code can be moved into a method and then called as many times as needed.
• The CourseAverage program of Section 2.11 suffers from a great deal of repetitive code.
• By moving this code to class methods, the program can be made shorter, as well as more
understandable and easier to modify.
Improving Clarity
• The original design of CourseAverage:
1. Print the introductory message (“Welcome to the CSc 2310 average calculation program”).
2. Prompt the user to enter eight program scores.
3. Compute the program average from the eight scores.
4. Prompt the user to enter five quiz scores.
5. Compute the quiz average from the five scores.
6. Prompt the user to enter scores on the tests and final exam.
7. Compute the course average from the program average, quiz average, test scores, and final exam score.
8. Round the course average to the nearest integer and display it.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 85
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Improving Clarity
• Most of the steps are fairly small, with the exception of steps 2 and 4.
• Helper methods that perform these steps will improve the program’s clarity.
• Both methods will return a double value:
private static double readProgramScores() { …
}
private static double readQuizScores() { …
}
Reducing Redundancy
• readProgramScores will consist of eight steps (one for each program score).
• Each step involves prompting the user to enter a number, reading the number as a string, and then converting the string to numeric form.
• Because the eight steps are nearly identical, it makes sense to write a helper method (readDouble) that performs a single prompt/read/convert step.
• readDouble can also be used to help write
readQuizScores.
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 87
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
Reducing Redundancy
• In the original CourseAverage program, a single prompt/read/convert step consists of statements such as the following:
SimpleIO.prompt("Enter Program 1 score: ");
String userInput = SimpleIO.readLine();
double program1 = Convert.toDouble(userInput);
• Since the prompt is different each time, it will need to be a parameter to readDouble.
• readDouble will need to return the value
entered by the user, after it has been converted to
double form.
Reducing Redundancy
• The three statements in the prompt/read/convert step will be replaced by a single method call:
program1 = readDouble("Enter Program 1 score: ");
• The readDouble method:
private static double readDouble(String prompt) { SimpleIO.prompt(prompt);
String userInput = SimpleIO.readLine();
return Convert.toDouble(userInput);
}
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 89
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
The Revised CourseAverage Program
• The revised CourseAverage program has three class methods: readProgramScores,
readQuizScores, and readDouble.
• Other changes to the program:
– Class variables are used as constants.
– Loops are used to read the program scores and grades.
– The readDouble method is used to help read the test
scores and the final exam score.
// Program name: CourseAverage2 // Author: K. N. King
// Written: 1998-04-21 // Modified: 1999-04-18 //
// Prompts the user to enter eight program scores (0-20), five // quiz scores (0-10), two test scores (0-100), and a final // exam score (0-100). Scores may contain digits after the // decimal point. Input is not checked for validity. Displays // the course average, computed using the following formula:
//
// Programs 30%
// Quizzes 10%
// Test 1 15%
// Test 2 15%
// Final exam 30%
//
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 91
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
public class CourseAverage2 { // Constants
private static final int NUM_PROGRAMS = 8;
private static final int NUM_QUIZZES = 5;
private static final int MAX_PROG_SCORE = 20;
private static final int MAX_QUIZ_SCORE = 10;
private static final double PROGRAM_WEIGHT = .30;
private static final double QUIZ_WEIGHT = .10;
private static final double TEST_WEIGHT = .15;
private static final double FINAL_EXAM_WEIGHT = .30;
public static void main(String[] args) { // Print the introductory message
System.out.println("Welcome to the CSc 2310 average " + "calculation program.\n");
// the average of the scores
double programAverage = readProgramScores() / NUM_PROGRAMS;
// Leave a blank line System.out.println();
// Prompt the user to enter quiz scores and compute the // average of the scores
double quizAverage = readQuizScores() / NUM_QUIZZES;
// Leave a blank line System.out.println();
// Prompt the user to enter scores on the tests and final // exam
double test1 = readDouble("Enter Test 1 score: ");
double test2 = readDouble("Enter Test 2 score: ");
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 93
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
// quiz average, test scores, and final exam score double courseAverage =
PROGRAM_WEIGHT * (programAverage / MAX_PROG_SCORE * 100) + QUIZ_WEIGHT * (quizAverage / MAX_QUIZ_SCORE * 100) +
TEST_WEIGHT * test1 + TEST_WEIGHT * test2 +
FINAL_EXAM_WEIGHT * finalExam;
// Round the course average to the nearest integer and // display it
System.out.println("\nCourse average: " +
Math.round(courseAverage));
}
// NAME: readProgramScores
// BEHAVIOR: Prompts the user to enter program scores // and computes their total.
// PARAMETERS: None
// RETURNS: Total of program scores
///////////////////////////////////////////////////////////
private static double readProgramScores() { double programTotal = 0.0;
for (int i = 1; i <= NUM_PROGRAMS; i++)
programTotal += readDouble("Enter Program " + i + " score: ");
return programTotal;
}
Copyright © 2000 W. W. Norton &
Company.
All rights reserved.
Java 95
Java ProgrammingProgramming
FROM THE BEGINNING FROM THE BEGINNING
// NAME: readQuizScores
// BEHAVIOR: Prompts the user to enter quiz scores and // computes their total.
// PARAMETERS: None
// RETURNS: Total of quiz scores
///////////////////////////////////////////////////////////
private static double readQuizScores() { double quizTotal = 0.0;
for (int i = 1; i <= NUM_QUIZZES; i++)
quizTotal += readDouble("Enter Quiz " + i + " score: ");
return quizTotal;
}
// NAME: readDouble
// BEHAVIOR: Prompts the user to enter a number, reads // the user's input, and converts it to double // form.
// PARAMETERS: prompt - the prompt to be displayed
// RETURNS: User's input after conversion to double
///////////////////////////////////////////////////////////
private static double readDouble(String prompt) { SimpleIO.prompt(prompt);
String userInput = SimpleIO.readLine();
return Convert.toDouble(userInput);
} }