Numerical Data: ©Themcgraw-Hill Companies, Inc. Permission Required For Reproduction or Display

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 126

Chapter 3

Numerical Data

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter 3 Objectives
After you have read and studied this chapter, you
should be able to

• Select proper types for numerical data.

• Write arithmetic expressions in Java.

• Evaluate arithmetic expressions, using the precedence


rules.

• Describe how the memory allocation works for objects


and primitive data values.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter 3 Objectives, cont.
After you have read and studied this
chapter, you should be able to

• Write mathematical expressions, using


methods in the Math class.

• Use the GregorianCalendar class in


manipulating date information such as year,
month, and day.

• Use the DecimalFormat class to format


numerical data.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter 3 Objectives, cont.
After you have read and studied this chapter, you
should be able to
• Convert input string values to numerical data.

• Apply the incremental development technique in writing


programs.

• (Optional) Describe how integers and real numbers are


represented in memory.

• Input data by using System.in and output data using


System.out.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
To compute the sum and the difference of x and y
in a program, we must first declare what kind of
data will be assigned to them.

After we assign values to them, we can compute


their sum and difference.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
When a declaration, such as
int x, y;
is made, memory locations to store data values for
x and y are allocated.

These memory locations are called variables, and


x and y are the names we associate with the
memory locations.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
A variable has three properties:
• A memory location to store the value.
• The type of data stored in the memory location.
• The name used to refer to the memory location.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
The syntax for declaring variables is
<data type> <variables>;
where <variables> is a sequence of identifiers
separated by commas.

Every variable we use in a program must be


declared.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
There are six numerical data types in Java:
• byte
• short
• int
• long
• float
• double

Data types byte, short, int, and long are for


integers.
Float and double are for real numbers.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
At the time a variable is declared, it can also be
initialized.
int count = 10, height = 34;

We assign a value to a variable by using an


assignment statement.

Do not confuse mathematical equality and


assignment. The following is not valid Java code:
4 + 5 = x;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
The only difference between a variable for
numbers and a variable for objects is the
contents in the memory locations.
• For numbers, a variable contains the numerical value
itself.
• For objects, a variable contains an address where the
object is stored.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.1
A diagram showing how two memory locations
(variables) are declared, and values are assigned
to them.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.2
A difference between object declaration
and numerical data declaration.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.1 Variables
We use the new command to create an object.

Objects are called reference data types, because


the contents are addresses that refer to memory
locations where the objects are actually stored.

Numerical data are called primitive data types.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.3
An effect of assigning the content of one
variable to another.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.2 Arithmetic Expressions
Arithmetic operators in Java

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.2 Arithmetic Expressions
An illustration of a subexpression in the expression
x + 3 * y

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.2 Arithmetic Expressions
Precedence rules for arithmetic operators and
parentheses

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.2 Arithmetic Expressions
Rules for arithmetic promotion

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.3 Constants
If we want a variable to remain fixed, we
use a constant.

A constant is declared in a manner similar


to a variable, but with the additional
reserved word final.

final double PI = 3.14159;


final int MONTHS_IN_YEAR = 12;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.3 Constants
If a literal constant contains a decimal
point, it is of type double by default.

To designate a literal constant of type


float, append a letter f or F to the
number:
2 * PI * 345.79F

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.3 Constants
Numbers in scientific notation, such as
Number x 10exponent

are expressed in Java using the syntax


<number> E <exponent>
12.40e+209
29.009E-102

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.4 Getting Numerical Input Values
Wrapper classes are used to perform necessary
type conversions, such as converting a String
object to a numerical value.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.4 Getting Numerical Input Values
/*
Chapter 3 Sample Program: Compute Area and
Circumference

File: Ch3Circle.java

*/

import javax.swing.*;
import java.text.*;

class Ch3Circle {
public static void main( String [] args ) {

final double PI = 3.14159;


String radiusStr;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.4 Getting Numerical Input Values
double radius, area, circumference;

radiusStr =
JOptionPane.showInputDialog(null, "Enter
radius:");

radius = Double.parseDouble(radiusStr);

//compute area and circumference


area = PI * radius * radius;
circumference = 2.0 * PI * radius;

JOptionPane.showMessageDialog(null, "Given
Radius: " + radius + "\n" + "Area: "
+ area + "\n" + "Circumference: " +
circumference);
}
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.4 Getting Numerical Input Values
An illustration of how the compiler interprets an
overloaded operator.

int x = 1;
int y = 2;
String output = “test” + x + y;

String output = x + y + “test”;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.4
The dialog that appears when the input value 2.35
was entered into the Ch3Circle program.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.5
The result of formatting the output values by using
a DecimalFormat object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.5 Standard Output
The showMessageDialog method is intended for
displaying short one-line messages, not for a
general-purpose output mechanism.

Using System.out, we can output multiple lines of


text to the standard output window.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.6
The standard output window for displaying multiple
lines of text.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.5 Standard Output
We use the print method to output a value.

The print method will continue printing from the


end of the currently displayed output.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.7
Result of executing System.out.print(“Hello, Dr.
Caffeine.”).

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.8
Result of sending five print messages to
System.out of Figure 3.7.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.5 Standard Output
The print method will do the necessary type
conversion if we pass numerical data.

We can print an argument and skip to the next line


so that subsequent output will start on the next
line by using println instead of print.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.9
The result of mixing print with four println
messages to System.out.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.6 Standard Input
The technique of using System.in to input data is
called standard input.

Associating a BufferedReader object to the


System.in object allows us to read a single line
of text, then convert it to a value of a primitive
data type.

Using the intermediate InputStreamReader object


allows us to read a single character at a time.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.10
How the sequence of I/O objects adds greater
capabilities.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.11
Sample interaction using System.in and
System.out.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.6 Standard Input
Calling the readLine method can result in
an error condition called an exception.

To avoid this problem, add the clause


throws IOException to the method
declaration whenever a method includes
a call to the readLine method.
public static void main(String [] args)
throws IOException {
...
String input = bufReader.readLine();
...
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.7 The Math Class
The Math class in the java.lang package contains
class methods for commonly used mathematical
functions.

Table 3.6 contains a partial list of class methods


available in the Math class.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.8 The GregorianCalendar Class
The GregorianCalendar class is useful in
manipulating calendar information such as year,
month, and day.

Note that the first month of the year, January, is


represented by 0.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.12
Result of running the Ch3TestCalendar program at
November 11, 2002, 6:13 p.m.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Program flow:
• Get three input values: loanAmount,
interestRate, and loanPeriod.
• Compute the monthly and total payments.
• Output the results.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.13
The object diagram for the program
LoanCalculator.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Steps of implementation:
1. Start with code to accept three input values.
2. Add code to output the results.
3. Add code to compute the monthly and total
payments.
4. Update or modify code and tie up any loose
ends.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Step 1 Development: Input Three Data Values

Call the showInputDialog method to accept three


input values:
• loan amount,
• annual interest rate,
• loan period.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
/*
Chapter 3 Sample Development: Loan Calculator (Step 1)

File: Step1/Ch3LoanCalculator.java

Step 1: Input Data Values

*/

import javax.swing.*;

class Ch3LoanCalculator {

public static void main (String[] args) {


double loanAmount,
annualInterestRate;

int loanPeriod;

String inputStr;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//get input values
inputStr = JOptionPane.showInputDialog(null,
"Loan Amount (Dollars+Cents):");

loanAmount = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Annual Interest Rate (e.g.,
9.5):");

annualInterestRate = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Loan Period - # of years:");

loanPeriod = Integer.parseInt(inputStr);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//echo print the input values
System.out.println("Loan Amount: $" +
loanAmount);
System.out.println("Annual Interest Rate: " +
annualInterestRate + "%");
System.out.println("Loan Period (years): " +
loanPeriod);
}
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Step 2 Development: Output Values

We must determine an appropriate format to


display the computed results, so that the results
will be comprehensible to the user.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 3.14
Two display formats: One with input values
displayed, and the other with only the computed
values displayed.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
/*
Chapter 3 Sample Development: Loan Calculator
(Step 2)

File: Step2/Ch3LoanCalculator.java

Step 2: Display the Result


*/

import javax.swing.*;

class Ch3LoanCalculator {

public static void main (String[] args) {


double loanAmount,
annualInterestRate;

double monthlyPayment,
totalPayment;

int loanPeriod;

String inputStr;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
3.9 Sample Development: Loan Calculator
//get input values
inputStr = JOptionPane.showInputDialog(null,
"Loan Amount (Dollars+Cents):");

loanAmount = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Annual Interest Rate (e.g.,
9.5):");

annualInterestRate = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Loan Period - # of years:");

loanPeriod = Integer.parseInt(inputStr);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//compute the monthly and total payments
monthlyPayment = 132.15;
totalPayment = 15858.10;

//display the result


System.out.println("Loan Amount: $" +
loanAmount);
System.out.println("Annual Interest Rate: " +
annualInterestRate + "%");
System.out.println("Loan Period (years): " +
loanPeriod);

System.out.println("\n"); //skip two lines

System.out.println("Monthly payment is $ " +


monthlyPayment);
System.out.println(" TOTAL payment is $ " +
totalPayment);
}
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Step 3 Development: Compute Loan Amount
Complete the program by implementing the
formula derived in the design phase.

We must convert the annual interest rate (input


value) to a monthly interest rate (per the formula),
and the loan period to the number of monthly
payments.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
/*
Chapter 3 Sample Development: Loan Calculator (Step 3)

File: Step3/Ch3LoanCalculator.java

Step 3: Compute the monthly and total payments


*/

import javax.swing.*;

class Ch3LoanCalculator {

public static void main (String[] args) {


final int MONTHS_IN_YEAR = 12;

double loanAmount, annualInterestRate,


monthlyPayment, totalPayment;

double monthlyInterestRate;

int loanPeriod, numberOfPayments;

String inputStr;
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
3.9 Sample Development: Loan Calculator
//get input values
inputStr = JOptionPane.showInputDialog(null,
"Loan Amount(Dollars+Cents):");
loanAmount = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Annual Interest Rate (e.g.,
9.5):");

annualInterestRate=Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Loan Period - # of years:");

loanPeriod = Integer.parseInt(inputStr);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//compute the monthly and total payments

monthlyInterestRate = annualInterestRate /
MONTHS_IN_YEAR / 100;

numberOfPayments = loanPeriod * MONTHS_IN_YEAR;

monthlyPayment =
(loanAmount * monthlyInterestRate) /
(1 - Math.pow(1/(1 + monthlyInterestRate),
numberOfPayments ) );

totalPayment = monthlyPayment * numberOfPayments;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//display the result
System.out.println("Loan Amount: $" +
loanAmount);
System.out.println("Annual Interest Rate: " +
annualInterestRate + "%");
System.out.println("Loan Period (years): " +
loanPeriod);

System.out.println("\n"); //skip two lines


System.out.println("Monthly payment is $ " +
monthlyPayment);
System.out.println(" TOTAL payment is $ " +
totalPayment);
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
Step 4 Development: Finishing Up

Finalize the program by making necessary


modifications or additions.

We will add a program description and format the


monthly and total payments to two decimal
places.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
/*
Chapter 3 Sample Development: Loan Calculator (Step 4)

File: Step4/Ch3LoanCalculator.java

Step 4: Finalize the program


*/
import javax.swing.*;
import java.text.*;

class Ch3LoanCalculator {

public static void main (String[] args) {


final int MONTHS_IN_YEAR = 12;

double loanAmount, annualInterestRate;

double monthlyPayment, totalPayment;

double monthlyInterestRate;

int loanPeriod, numberOfPayments;

String inputStr;

DecimalFormat df = new DecimalFormat("0.00");


©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
3.9 Sample Development: Loan Calculator
//describe the program
System.out.println("This program computes the
monthly and total");

System.out.println("payments for a given loan


amount, annual ");

System.out.println("interest rate, and loan


period.");

System.out.println("Loan amount in dollars and


cents, e.g., 12345.50");

System.out.println("Annual interest rate in


percentage, e.g., 12.75");

System.out.println("Loan period in number of


years, e.g., 15");

System.out.println("\n"); //skip two lines

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//get input values
inputStr = JOptionPane.showInputDialog(null,
"Loan Amount(Dollars+Cents):");

loanAmount = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Annual Interest Rate (e.g.,
9.5):");

annualInterestRate = Double.parseDouble(inputStr);

inputStr = JOptionPane.showInputDialog(null,
"Loan Period - # of years:");

loanPeriod = Integer.parseInt(inputStr);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//compute the monthly and total payments

monthlyInterestRate = annualInterestRate /
MONTHS_IN_YEAR / 100;

numberOfPayments = loanPeriod * MONTHS_IN_YEAR;

monthlyPayment =
(loanAmount * monthlyInterestRate) /
(1 - Math.pow(1/(1 + monthlyInterestRate),
numberOfPayments ) );

totalPayment = monthlyPayment * numberOfPayments;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


3.9 Sample Development: Loan Calculator
//display the result
System.out.println("Loan Amount: $" +
loanAmount);
System.out.println("Annual Interest Rate: " +
annualInterestRate + "%");
System.out.println("Loan Period (years): " +
loanPeriod);

System.out.println("\n"); //skip two lines

System.out.println("Monthly payment is $ "


+ df.format(monthlyPayment));
System.out.println(" TOTAL payment is $ "
+ df.format(totalPayment));
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter Four

Defining Your Own Classes

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter 4 Objectives
After you have read and studied this chapter, you
should be able to
• Define an instantiable class with multiple
methods and constructors.
• Differentiate the local and instance variables.
• Define and use value-returning methods.
• Distinguish private and public methods.
• Distinguish private and public data members.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Chapter 4 Objectives, cont.
After you have read and studied this chapter, you
should be able to
• Describe how the arguments are passed to the
parameters in method definitions.
• Describe how the result is returned from a
method.
• Define a reusable class for handling input
routines.
• Define an instantiable main class.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Learning how to define instantiable classes is the
first step toward mastering the skills necessary in
building large programs.
A class is instantiable if we can create instances of
the class. The DecimalFormat,
GregorianCalendar, and String classes are all
instantiable classes, while the Math class is not.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Currency converter example: We need two
methods for conversion: fromDollar and toDollar.

CurrencyConverter yenConverter;
double amountInYen, amountInDollar;
yenConverter = new CurrencyConverter( );
...
amountInYen = yenConverter.fromDollar(200); //from dollar
to yen

amountInDollar = yenConverter.toDollar(15000);
//from yen to dollar

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Since the exchange rate fluctuates, we
need a method to set the exchange
rate.
CurrencyConverter yenConverter;
yenConverter = new CurrencyConverter( );
yenConverter.setExchangeRate(130.77);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Class diagram for a CurrencyConverter object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.1
A program template for a class definition.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Once the CurrencyConverter class is
defined, we can use its multiple
instances.
CurrencyConverter yenConverter, markConverter;
double amountInYen, amountInMark, amountInDollar;

yenConverter = new CurrencyConverter();


yenConverter.setExchangeRate(130.77);

markConverter = new CurrencyConverter( );


markConverter.setExchangeRate(1.792);

amountInYen = yenConverter.fromDollar( 200 );


amountInMark = markConverter.fromDollar( 200 );

amountInDollar = yenConverter.toDollar( 10000 );


amountInMark = markConverter.fromDollar(amountInDollar);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.2
Every object of a class has its own copy of
instance variables.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
Syntax for defining a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
If the method declaration includes the static
modifier, it is a class method.

Class methods can access only class variables


and constants.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
If the method declaration does not include the
static modifier, it is an instance method.

Instance methods can access class variables and


constants, as well as instance variables.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.1 Defining Instantiable Classes
We call a method that returns a value a
value-returning method, or non-void
method.
A value-returning method must include a
return statement in the following
format:
return <expression> ;

public double toDollar( double foreignMoney )


{
return (foreignMoney / exchangeRate);
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
A constructor is a special method that is executed
when a new instance of the class is created.

The purpose of the constructor is to initialize an


object to a valid state. Whenever an object is
created, we should ensure that it is created in a
valid state by properly initializing all data
members in a constructor.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
The name of a constructor must be the same as
the name of the class.

If no constructor is defined for a class, then the


Java compiler will include a default constructor.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
Syntax of a constructor.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
The default constructor will have the
following form:
public <class name> ( )
{
}

public CurrencyConverter( )
{

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
A constructor does not have a return type.

It is possible to create multiple constructors for a


class, as long as the constructors have either
• A different number of parameters, or
• Different data types for the parameters if the number of
parameters is the same.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.2 Instantiable Classes and Constructors
Examples of multiple constructors

public MyClass( int value ) { … }


public MyClass( ) { … }
public MyClass( float value ) { … }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.3 Information Hiding and
Visibility Modifiers
Public methods of a class determine the behavior
of its instances.

Internal details are implemented by private


methods and private data members.

Declaring the data members private ensures the


integrity of the class.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.3 Information Hiding and
Visibility Modifiers
The modifiers public and private designate the
accessibility of data members and methods.

If a class component (data member or method) is


declared private, no outside methods can access
it.

If a class component is declared public, any


outside method can access it.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.3 Information Hiding and
Visibility Modifiers
Class constants may be declared public because:
• A constant is “read only” by nature
• A constant is a clean way to make characteristics of
the instances known to client programmers.

Public class data members are accessed by the


syntax
<class name>.<class data members>

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.3 Information Hiding and
Visibility Modifiers
Plus and minus signs designate public and private
components, respectively.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
A local variable is a variable that is declared within
a method declaration.

Local variables are accessible only from the


method in which they are declared.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
Memory space for local variables is allocated only
during the execution of the method. When the
method execution completes, memory space will
be cleared.

The parameters of a method are local to the


method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
Sample method:

public double fromDollar( double dollar )


{
double amount, fee; Parameter
Parameter
Local
Local
Variables
Variables
fee = exchangeRate - feeRate;
amount = dollar * fee;

return amount;
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.3
Memory space for local variables and parameters
is allocated and erased.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.3 cont.
Memory space for local variables and parameters
is allocated and erased.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
When a method is called, the value of the
argument is passed to the matching parameter,
and separate memory space is allocated to store
this value.

This way of passing the value of arguments is


called a pass-by-value, or call-by-value, scheme.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
The data type of the argument must be
assignment-compatible with the data type of the
matching parameter.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.4
Memory space for the parameters is allocated and
erased.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.4 cont.
Memory space for the parameters is allocated and
erased.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
Parameters and return types are designated in the
program diagram:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.4 Local Variables,
Return Values, and Parameter Passing
The same designation applies to data members:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.5 Accessors, Mutators, and Overloaded
Methods
A set method is called a mutator because it
changes the property of an object.

An accessor is a method that returns a property of


an object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.5 Accessors, Mutators, and Overloaded
Methods
Like constructors, methods may have the same
name as long as the methods have either
• A different number of parameters, or
• Different data types for the parameters if the number of
parameters is the same.

The methods with the same name are called overloaded


methods.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.5 Accessors, Mutators, and Overloaded
Methods
Dot notation is optional when you call a method
from another method if the two methods belong
to the same object.

If dot notation is used, use the reserved word this


to refer to the same object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.5
Calling a method belonging to the same object vs.
calling a method belonging to a different object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.6 Passing and Returning Objects
Passing and returning objects follow the same
process as passing and returning primitive data
types.

The only difference is that with objects, the value


being passed is the reference (or address) to an
object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.6 Passing and Returning Objects
When a variable is an object name, the value of
the variable is the address in memory where the
object is stored.

The effect of passing this value, or reference, is to


have two variables (object names) referring to the
same object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.6
How an object is passed to a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.6 cont.
How an object is passed to a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.7
How an object is passed to a method (cont.).

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.7 cont.
How an object is passed to a method (cont.).

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.8
How an object is returned from a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.8 cont.
How an object is returned from a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.9
How an object is returned from a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.9 cont.
How an object is returned from a method.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.7 Modularizing the Input Routine
Functionality
When a common task is repeated over and over, it
is best to capture the common task into a class
and use an instance of the class to perform the
task.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.8 Organizing Classes into a Package
1. Include the statement
package <package name>
as the first statement of the source file for the class
you are packaging.

2.The class declaration must include the visibility


modifier public.

3. Create a folder with the same name as the


package name.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.8 Organizing Classes into a Package
4. Place the class into the folder and compile it.

5. Modify the CLASSPATH environment variable to


include the folder that contains the package.

• Note that the steps to change the CLASSPATH


environment variable are different for each
platform and IDE.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.9 Sample Development: Defining and
Using Instantiable Classes
Example: Loan and LoanCalculator classes.

1. Consider problem statement.

Write a loan calculator program that computes


both monthly and total payments for a given
loan amount, annual interest rate, and loan
period.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.9 Sample Development: Defining and
Using Instantiable Classes
Develop overall plan:

1. Get three input values: loanAmount,


interestRate, and loanPeriod.
2. Compute the monthly and total payments.
3. Output the results.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.9 Sample Development: Defining and
Using Instantiable Classes
Five steps of implementation:

1. Start with the main class and a skeleton of the


LoanCalculator class.
• The skeleton class will include only an
object/variable declaration and a constructor to
create objects.
• Define a temporary placeholder for the Loan class.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.9 Sample Development: Defining and
Using Instantiable Classes
Five steps of implementation:

2. Implement the input routine to accept three input


values.

3. Implement the output routine to display the


results.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.9 Sample Development: Defining and
Using Instantiable Classes
Five steps of implementation:

4. Implement the computation routine to compute


the monthly and total payments.

5. Finalize the program, implementing any


remaining temporary methods and adding
necessary methods as appropriate.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.10
The program diagram for design alternative 1.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Fig. 4.11
The program diagram for alternative design 2.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


4.10 Making an Instantiable Class the Main
Class
LoanCalculator example: Copy the main method of
LoanCalculatorMain and paste it to the LoanCalculator
class:

//Instantiable Main Class


class LoanCalculator {

//exactly the same code as before comes here

public static void main (String [ ] args) {


LoanCalculator loanCalculator;
loanCalculator = new LoanCalculator( );
loanCalculator.start( );
}
}

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.


Javadoc comments
Javadoc comments begin with /** and end with */.
Javadoc tags are special markers that begin with
@. For example:
• @author
• @param
• @return

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.

You might also like