SlideShare a Scribd company logo
The Java Learning Kit: Chapter 5 – Methods and Modularity
Copyright 2015 by C. Herbert, all rights reserved.
Last edited January, 2015 by C. Herbert
This document is a chapter from a draft of the Java Learning
Kit, written by Charles Herbert, with editorial input from Craig
Nelson, Christopher Quinones, Matthew Staley, and Daphne
Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during
the Spring 2015 semester.
This material is protected by United States and international
copyright law and may not be reproduced, distributed,
transmitted, displayed, published or broadcast without the prior
written permission of the copyright holder. You may not alter
or remove any trademark, copyright or other notice from copies
of the material.
The Java Learning Kit:
Chapter 5
Methods and Modularity
Lesson 5.1 – User Created Methods in Java
Lesson 5.2 – Method Parameters
Lab 5A – Examining code with Several Methods
Lesson 5.3 – Top-Down Design and Modular Development
Lab 5B – Methods and Parameter Passing
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 2
Contents
Chapter 5 Learning Outcomes
...............................................................................................
..................... 3
User Created Methods in Java
......................................................................................... 4
Method Modifiers
...............................................................................................
................................ 4
Return Type
...............................................................................................
......................................... 6
Other method modifiers
...............................................................................................
...................... 7
Method Parameters
...............................................................................................
............................. 7
Invoking a Method and Parameter Passing
......................................................................................... 7
Method Documentation
...............................................................................................
...................... 9
CheckPoint 5.1
...............................................................................................
................................... 10
Lab 5A – Examining code with Several Methods
................................................................................... 11
Top-Down Design and Modular Development
.............................................................. 13
CheckPoint 5.2
...............................................................................................
................................... 15
Lab 5B – Methods and Parameter Passing
............................................................................................
16
Key Terms
...............................................................................................
.............................................. 21
Chapter Questions
...............................................................................................
................................. 21
Chapter Exercises
...............................................................................................
................................... 22
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 3
The Java Learning Kit: Chapter 2
Reading, Writing, and Arithmetic
This chapter introduces user-created methods in Java, along
with the accompanying
techniques of modular development and top-down design, also
known as structured
decomposition or functional decomposition.
Parameter passing between methods and polymorphic method
overloading are also
discussed.
Chapter 5 Learning Outcomes
Upon completion of this chapter students should be able to:
Oracle’s Java
Tutorials.
the difference
between a formal parameter list and an actual parameter list.
-down design of an algorithm, also
known as
structured decomposition or functional decomposition.
and several
advantages of
developing software in smaller modules.
demonstrating good
modular design and the proper use of parameter passing
between methods.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 4
User Created Methods in Java
So far we have only created software with a single method, the
main method in the single class in each
Java application we created. We have invoked other methods
from other classes, such as the Math class
and the Scanner class, but we have only created one method at a
time in our applications. Now we will
begin to work with multiple methods of our own.
The code for each method in Java software is defined in a
method declaration within a class. A method
declaration defines a method, with a method header, followed
by a block of code marked by braces.
According to Oracle’s Java tutorials, a method declaration has
six components – the five parts of the
method header and the method’s block of code1. A Java method
header includes method modifiers
(such as public and static), the return type of the method, the
method name, a set of parentheses which
contains the method’s parameters, and an exception list. The
parentheses are blank if there are no
parameters. In general the parts of a method header look like
this:
[modifiers] [return type] method name(formal parameter list)
[exception list]
Here is an example. This method has no exception list after the
parameter list. If you do see the word
throws after a parameter list, then that is the beginning of the
exception list, which is also known as a
thrown exception clause. We will learn about exceptions later in
the course.
public double overTime(double hours, double rate) {
double overtimeHours;
double overtimePay;
overtimeHours = hours - 40;
overtimePay = overtimeHours *rate * 1.5;
return overtimePay;
} // end (overtime(( double hours, double rate)
Method Modifiers
Method modifiers provide the compiler with information about
the nature of the method. The most
common method modifier is called the access modifier, which
sets the access level for the method. Java
methods may have public, private, or protected access.
any other software.
within the class which contains the
method.
1 See:
http://docs.oracle.com/javase/tutorial/java/javaOO/methods.htm
l
method header
parameter list return type access modifier method name
Figure 1 – parts of a
method header
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 5
subclasses of a class may invoke protected
methods. We learn about subclasses later in the semester when
we learn about inheritance.
Why Java Applications Need a Public Static Void Main()
Method
Every java application must start somewhere.
A Java application can contain many methods in many different
classes and can also import
methods from classes that are not part of the application’s own
source code, but that are defined
elsewhere.
At least one class in a Java application must have the same
name as the application’s software
package. This class must contain a method named main, which
will be the method that is executed
when the software application runs. The main method will
contain any calls or references to other
methods used within the application.
A Java application’s main method must be public, which means
it is available to be run from outside
of its own software package. This is necessary so that the
operating system can start the application
by running the main method. This means that the access
modifier public must be included in a main
method’s header.
An application’s main method is a class-level method,
associated with the overall application’s and
not with an instance of a class, therefore its header must have
the access modifier static, which
identifies class-level methods, variables, and so on.
The main method for a java application does not return any
values. Hence it must be marked with
the access modifier void in the method’s header, which
indicates it does not return any user defined
values. Actually, when a java application terminates it will
send a code to the operating system to
indicate whether or not the application terminated normally.
However, this message passing
happens automatically, and we do not need to be concerned
about it, at least not for now.)
Putting all of this together, the modifiers public, static and void
must come before the method name
in the method header for a main method. For example, a
payroll application whose application
software package is named Payroll, must have a payroll class
with the following method:
public static void main( String[] args) {
. . . method block of code follows . . .
} // end main()
The parameter for the main method is a String array of
arguments, which is why main methods
have the default parameter String[] args. (The terms parameter
and argument mean almost the
same thing, and are often used interchangeably.) Often this
parameter goes unused, but it is there
to enable operating system and the method to communicate with
one another.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 6
Another common method modifier is the static modifier.
According to the JLS, a method that is declared
static is called a class method. A static method is associated
with the class and not with an instance of
the class. It is invoked by using the class name, and not the
instance name, as part of its qualified name.
The main methods in the software we have written so far have
been declared public static void main(…).
We have also seen static methods in the Math class. Methods
such as Math.sqrt() and Math.random()
are class level methods that have been invoked using the name
of the class – the Math class.
The Scanner class methods we have used were not class level
methods. They were invoked using the
name of an instance of the class. We had to declare a new
instance of the Scanner class associated with
a particular input stream before we could use methods such as
nextLIne() in the example below. If the
static modifier is missing, then the method is an instance
method. If the static modifier is present, it is a
class method.
public static void main(String args[]) {
String name;
Scanner kb = new Scanner(System.in);
// say hello to the user and ask for the user’s name
System.out.println("Hello, please enter your name: ");
name = kb.nextLine();
. . . // the method continues . . .
Return Type
The return type in a method header declares the data type of the
value the method returns, or uses the
keyword void to indicate that the method does not return a
value. A method that does not return a
value is often called a void method. A void method is invoked
from another method by using the void
method’s name as if it is a new Java instruction.
A method that returns a value can called from anyplace in
another Java method where a variable or
literal of the same data type can be used. For example, the
Math.sqrt() method returns a value of data
type double. Therefore, it can be called from any place that a
variable type double or a double literal can
be used, such as in a math expression.
Methods that return a value, such as the
Math.sqrt() method, are often called inline
methods, because they can be invoked in a
Java statement “inline”, as shown on the left.
double result;
double num1;
result = 3 * num1 + 4;
result = 3 * Math.sqrt(10) + 4;
The nextLine() method that is invoked from the main() method
in Figure 2, above, has a return type of
String, so it can be used in a Java statement anyplace that a
String value can be used. In this example,
the value returned by the method is assigned to the String
variable name.
Figure 2 – part of
a main() method
The static modifier identifies the main()
method as a class-level method.
The nextLine() method is a instance method,
invoked using the name of the instance of
the Scanner class to which it applies, kb.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 7
Other method modifiers
There are several other modifiers, such as abstract, native,
strictfp, and synchronized, that can be used
in Java methods headers in addition to modifiers and return
types discussed here. They are beyond what
we need to use for now, but are listed and described online at:
http://docs.oracle.com/javase/tutorial/reflect/member/methodMo
difiers.html
Method Parameters
The list of variable declarations in parentheses following the
name of the method is the formal
parameter list. Formal parameters are local variables that will
hold the values passed to the method
when the method is invoked. They are declared in the method
header by listing the data types and
names of the variables. They may be used in the method just as
any other local variables may be used.
The scope of the variables declared in a formal parameter list is
the body of the method in whose
header the list appears.
In the overtime example shown again in Figure 3, the double
variables hours and rate are formal
parameters, which are used as local variables within the method.
Values will be passed to initialize
these variables when the method is invoked from another
method. The parameters that are passed to a
method are also called the arguments of a method.
/****************************************************
*************************/
/* The overtime method calculates the total overtime pay
following the time
* and a half for overtime rule. The result is to be added to the
regular pay
* for 40 hours.
*
* method parameters:
* double hours -- hours worked this week – usually close to
40.0
* double rate -- employee's pay rate a decimal values usually
less than 100
*
* The method returns the total overtime pay for hours above 40
as a double.
*/
public double overTime( double hours, double rate) {
double overtimeHours; // hours worked beyond 40
double overtimePay; // pay for overtime hours
// calculate overtime hours and pay
overtimeHours = hours - 40;
overtimePay = overtimeHours *rate * 1.5;
return overtimePay;
} // end overtime (double hours, double rate)
/****************************************************
*************************/
Invoking a Method and Parameter Passing
There are two ways a method may be invoked from another
method:
a Java statement;
user-created instruction in the
Java language.
The following examples show how to invoke methods.
Figure 3 – a user-
defined method
http://docs.oracle.com/javase/tutorial/reflect/member/methodMo
difiers.html
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 8
Example 1 - is a declaration for a method that returns a value.
We can see from the method header that
its return type is int. It also takes two integer parameters, a and
b.
// this method returns the lesser of two integer values
public int lesser( int a, int b) {
if ( b < a)
return b;
else
return a;
} // end lesser()
The method may be used anyplace in a Java expression where an
integer value can be used, such as in
the following statement in another method:
sum = grade 1 + grade2 + lesser(grade3, grade4);
In Java, parameters can be passed by value. Parameter passing
by value means that the values
specified in the actual parameter list are passed to the variables
declared in the formal parameter list.
When a method is invoked, the data types of the actual
parameters must match those of the formal
parameters and the actual parameters must be in the same order
as the formal parameters.
In this case, the values of the variables grade3 and grade4 are
the actual parameters for this invocation
of the method. They are passed to the variables a and b in the
method lesser(). The values of the
variables grade3 and grade4 are used to initialize the variables a
and b in the method lesser().
91
93
grade3
grade4
91
93
a
b
memory space for main() memory space for lesser()
94
87
grade1
grade2
If grade3 = 91 and grade4 = 93, then 91 is passed to a and 93 is
passed to b. There is no connection
between the variables in the two methods – the values from one
are simply passed to the other.
Example 2 - a value returning method named square
// this method returns the square of a double value
public double square( double x) {
return x * x;
} // end square()
The square() method is invoked in each of the following
statements:
dist = Math.sqrt( square(dx) + square(dy) );
area = square(s);
area = square(2.5);
actual parameters
type
Figure 4 – a method that
returns an int value
Figure 5 – parameter
passing by value
Figure 6 – a method that
returns a double value
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 9
The square() method is called four times, twice in the first
statement, once in the second statement.,
and once in the third statement. Notice that the third statement
uses the value 2.5 as an actual
parameter – no variable is used. This is perfectly acceptable
when passing by value, as Java does.
In the first statement, the value of dx is passed to square() and
the return value is used in place of the
method call square(dx), then the value of dy is passed to
square() and the return value is used in place of
the method call square(dy).
In the second statement, the value of s is passed to the square()
method and the formal parameter x is
initialized to the value of s. Area will be equal to s2.
In the third statement, the value 2.5 is passed to square and the
formal parameter x is initialized to 2.5.
Area will be equal to 2.52, which is 6.25.
*****************************************************
********************************
Example 3 - a void method
public void printCheck(String name, double netPay) {
System.out.println("Pay to the order of " + name);
System.out.printf("%8.2f”, netPay )
} // end printCheck()
A void method is used as if it is a new instruction in the Java
language:
printCheck(name, netPay);
printCheck(“Mary Jones”, 371.28);
printCheck( (fname + “ “ + lname), net);
In each case, the program will invoke printCheck(), passing the
values to the method. The method uses
the data to print the checks, but no value is returned to the
calling method.
The parameter passing works the same with void methods as
with value returning methods: the values
in the actual parameter list are used to initialize the variables in
the formal parameter list. In the first
statement above, the values of the variables name and netPay in
the calling method are used to
initialize empName and netPay in the printCheck() method.
Even though the two variables netPay have
the same name, they are still different variables not connected
to one another in any way. The value of
one is simply used to initialize the other.
In the second printCheck() statements above, literal values are
specified. These values will be used to
initialize name and netPay when printCheck() is invoked.
Method Documentation
The version of the overtime method shown in Figure 3 is
reasonably well-documented. Documentation
is an important part of programming. Method documentation is
an important part of object-oriented
programming.
Information in a comment describing each method should
include the method’s:
nctions
Figure 7 – a void method
– used “inline” as if it is
a new Java instruction
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 10
A method’s entry conditions include information about the
variables in the formal parameter list – such
as the range of values for each parameter – along with any other
special conditions that must be set
before the method runs. In the case of the overTime method in
Figure 3, the expected values of the
variables hours and rate are listed, but no special conditions are
mentioned.
The method documentation should briefly describe what the
method does and how the method
functions. It should tell the reader if any new or unusual
techniques are used in the method. If there
are several different way to do something, then the
documentation should be clear about which way is
used in this method. The documentation for the overTime()
method in Figure 3 makes it clear that the
“time and a half for overtime” rule was applied, and that the
method returns the total pay for all
overtime hours, not just the added half.
A method’s exit conditions should describe what value, if any, a
method returns and anything else the
method does that has an effect outside of the method. Does it
open a new I/O stream? Does it turn a
hardware device on or off? If it does anything with an effect
that will be present after the method runs,
then the exit conditions should say so. In the case of the
overtime method in Figure 3, the only exit
condition is that it returns a value. The data type and meaning
of the value returned should be clearly
described.
You should also do something with the documentation to clearly
separate one method from another in
a class. Programming styles differ, so there are many ways to
do this. In the case of the overtime
method, a line of stars and then a blank line are immediately
placed at the end of the method. This
makes it easier for a reader to distinguish between methods.
Remember, the documentation will be stripped from the code
when the software is compiled. It’s there
to make it easier for people to read and understand the code,
including you as the author of the code
who may need to come back to a method months or years later
and will need to understand how it
works. All documentation should be clear and reasonably
concise, but ease of understanding is the
most important factor. It is worth the time to make sure that
readers can understand your code.
CheckPoint 5.1
1. What are the six parts of a method declaration in Java,
according to Oracle’s Java Tutorials?
2. What do the method modifiers public, private, and static each
mean in a method declaration?
3. What is a void method and how is it invoked form another
method?
4. How is a value returning method invoked from another
method?
5. What is a formal parameter list and how does it correspond to
an actual parameter list?
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 11
Lab 5A – Examining code with Several Methods
The following source code is in the NetBeans project
PayMethods, included in the file payMethods.zip in
the files for Week 5 in Canvas. It demonstrates the use of a
value returning method and a void method.
Your task is to download the file, unzip the NetBeans project,
then open it in NetBeans and examine the
code. You should be able to see how the a value returning
method and a voids method are invoked from
main, and how parameters are passed from the main method to
calculateGross() and to payrollReport().
Notice that calculateGross() and payrollReport() are both static
methods. This is because main() is a
static method, and static methods cannot call instance methods.
You should run the program to see how it works, then perhaps
try changing some of the actual
parameters to specific values to see how that works.
Notice the modularity of the program – we could change the
print report formats, for example, without
messing with the main() method. We could also modify the way
overtime is calculated without
changing any other methods.
package paymethods;
import java.util.Scanner;
/* CSCI 111 Fall 2013
* Sample program - payroll methods
* This program has an example of a value returning method and
a void method
*/
public class PayMethods {
public static void main(String[] args) {
String fname; // employee's first name
String lname; // employee's last name
double hours; // hours worked in the week
double rate; // hourly pay rate
double gross; // gross pay (hours * rate) + overtime
// set up input stream from the keyboard
Scanner keyboard = new Scanner(System.in);
// get employee's first name
System.out.print("Please enter the employee's first name: " );
fname = keyboard.next();
// get employee's last name
System.out.print("Please enter the employee's last name: " );
lname = keyboard.next();
// get employee's hours
System.out.print("Please enter the hours for " + fname +" " +
lname+ ": ");
hours = keyboard.nextDouble();
// get employee's rate
System.out.print("Please enter the pay rate for " + fname +" "
+ lname+ ": ");
rate = keyboard.nextDouble();
Figure 8 – a payroll
program composed
of several methods
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 12
// call method to calculate gross
// This value returning method is used inline, gross is set to
the value it returns
gross = calculateGross(hours, rate);
// call method to print payroll report
// this void method is used as if it is a new instruction in Java
// the actual parameters must correspond with the method's
formal parameter list
payrollReport(fname, lname, hours, rate, gross );
} // end main()
/****************************************************
*************************/
/* This method calculates gross pay using the time and a half
for overtime rule.
* it has two parameters,
* the hours worked during the week double hrs
* the pay rate double rt
*
* it returns the gross pay
*/
public static double calculateGross(double hrs, double rt ) {
double gr; // gross pay
double ot; // overtime pay
gr = hrs * rt;
if (hrs > 40)
ot = (hrs-40) * .5 * rt; // overtime bonus
else
ot = 0;
gr = gr + ot;
return gr;
} // end calculateGross
/****************************************************
*************************/
/* this method prints a payroll report
* it takes four parameters,
* employeee's first name String fname
* employee's last name String lname
* the hours worked during the week double hrs
* the pay rate double rate
*/
public static void payrollReport(String fname, String lname,
double hrs, double rt, double gross ) {
// print the payroll report
System.out.printf("%n%-12s%-12s%8s%8s%9s%n", "first",
"last",
"Hours", "Rate", "Gross");
System.out.printf("%-12s%-12s%8.2f%8.2f%,9.2f%n", fname,
lname,
hrs,rt, gross);
} // end payrollReport()
} // end class
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 13
Top-Down Design and Modular Development
It’s hard to solve big problems.
It’s easier to solve small problems than it is to solve big ones.
Computer programmers use a divide and conquer approach to
problem solving:
This process is a combination of techniques known as top-down
design and modular development.
Top-down design is the process of designing a solution to a
problem by systematically breaking a
problem into smaller, more manageable parts.
First, start with a clear statement of the problem or concept – a
single big idea. Next, break it down into
several parts. If any of those parts can be further broken down,
then the process continues until you
have a collection of parts that each do one thing.
The final design might look something like this organizational
chart, showing the overall structure of
separate units that form a single complex entity.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 14
An organizational chart is like an upside down tree, with nodes
representing each process. The leaf
nodes are those at the end of each branch of the tree. The leaf
nodes represent modules that need to
be developed and then recombined to create the overall solution
to the original problem.
Top-down design leads to modular development.Modular
development is the process of developing
software modules individually, then combining the modules to
form a solution to an overall problem.
Figure 9 – an organizational chart showing
units that form a single complex entity
Figure 10 the leaf nodes of
an organizational chart
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 15
Modular development facilitates production of computer
software because it:
… makes a large project more manageable.
Smaller and less complex tasks are easier to understand than
larger ones and are less
demanding of resources.
… is faster for large projects.
Different people can work on different modules, and then put
their work together. This means
that different modules can be developed at the same time, which
speeds up the overall project.
… leads to a higher quality product.
Programmers with knowledge and skills in a specific area, such
as graphics, accounting, or data
communications, can be assigned to the parts of the project that
require those skills.
…makes it easier to find and correct errors.
Often, the hardest part of correcting an error in computer
software is finding out exactly what is
causing the error. Modular development makes it easier to
isolate the part of the software that
is causing trouble.
… increases the reusability of solutions.
Solution
s to smaller problems are more likely to be useful elsewhere
than solutions to bigger
problems. They are more likely to be reusable code. Reusable
code is code that can be written
once, then called upon again in similar situations. It makes
programming easier because you
only need to develop the solution to a problem once; then you
can call up that code whenever
you need it. Modules developed as part of one project, can be
reused later as parts of other
projects, modified if necessary to fit new situations. Over time,
libraries of software modules for
different tasks can be created. Libraries of objects can be
created using object-oriented
programming languages.
Most computer systems are filled with layers of short
programming modules that are constantly reused
in different situations. Our challenge as programmers is to
decide what the modules should be. Each
module should carry out one clearly defined process. It should
be easy to understand what the module
does. Each module should form a single complete process that
makes sense all by itself.
Top-down development is used to figure out what the modules
are needed in a software development
project and how they should be organized. Modular
development involves building those modules as
separate methods, then combining them to form a complete
software solution for the project.
CheckPoint 5.2
1. What are Java’s nine built-in data types and how do they fit
into four major categories?
2. Which Java built-in data type is not a primitive data type?
3. How do each of Java’s integer data types differ from one
another?
4. What is a literal and how are literals represented for different
built-in data types?
5. Describe the formats used to store floating point data in
memory.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 16
Lab 5B – Methods and Parameter Passing
In this example we will develop a modular solution for a
problem that is similar to the homework
assignment from chapter 3.
We wish to input the x and y coordinates for two points in the
Cartesian plane, and find the distance
between the two, then print a report telling the user the distance
between the two points and the
quadrant that each point is in.
The distance between two points whose coordinates are (x1,y1)
and (x2, y2) is √��2 + ��2 where Δx
is the difference between the two x coordinates (x1- x2)and Δy
is the difference between the y
coordinates (y1- y2).
The example on the right also shows us
that the quadrants of a Cartesian plane
are numbered I through IV, with the
following properties:
-negative,
the point is in Quadrant I.
f x is negative and y is non-negative,
the point is in Quadrant II
the point is in Quadrant III.
-negative and y is negative,
the point is in Quadrant IV.
Y axis
X axis
(4,4)
Δy = 8
(0,0)
Quadrant IQuadrant II
Quadrant III Quadrant IV
(-2,-4) Δx = 6
Once we understand the specifications, we can make an outline
of what our software should do:
1. get the coordinates of two points: (x1, y1) and (x2, y2)
2. calculate the distance between the two points:
-x2; deltaY = y1-y2;
3. determine which quadrant (x1, y1) is in:
drant III
4. determine which quadrant (x2, y2) is in:
5. print results
Figure 11 – two points
in a Cartesian plane
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 17
The similarity of steps 3 and 4 indicate that this would be good
place for reusable code – one method
that can be used twice, but each time with different values
passed to the method. Step 2 is also a good
place for a method, with the details of the calculation in the
method.
Step 1 might seem like a good place for a method – we get four
numbers from the user, each in the
same manner. However, remember that methods can only return
one value, so we really don’t gain
much by making this a separate method. It is a judgment call
and a matter of programming style – it
could be done with four calls to one method, but in this case we
will use four different sets of
statements in the main method.
Here in the design of our software, listing descriptions of the
methods with return types and formal
parameters:
Void main() method
Double CalcDistance(double x1, double y1, double x2, double
y2) method
ulate deltaX
String findQuadrant( double x, double y)
X >=0) && (Y<0) Q =“Quadrant IV”
The code in Figure 12 starting on the next page was developed
from these specifications.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 18
/*
* program to calculate the distance between two points
* CSCI 111 Fall 2103
* last edited Sept 24, 2013 by C. Herbert
*/
package twopoints;
import java.util.Scanner;
public class TwoPoints {
// The main method gets x and y for two points
// Calls methods to calculate the distance between the two
// and to determine the quadrant of each point
// then outputs the result
public static void main(String[] args) {
//declare variables
double x1,y1,x2,y2; // coordinates of (x1,y1) and
(x2,y2)
double dist; // distance between (x1,y1) and
(x2,y2)
String Q1, Q2; // quadrant containing (x1,y1) and
(x2,y2)
// set up instacne of Scanner for input
Scanner kb = new Scanner(System.in);
// get input in prompt & capture pairs
System.out.print("Enter the x coordinate of point 1 :");
x1 = kb.nextDouble();
System.out.print("Enter the y coordinate of point 1 :");
y1 = kb.nextDouble();
System.out.print("Enter the x coordinate of point 2 :");
x2 = kb.nextDouble();
System.out.print("Enter the y coordinate of point 2 :");
y2 = kb.nextDouble();
// call calcDistance()
dist = calcDistance( x1, y1, x2, y2);
// call findQuadrant(point1)
Q1 = findQuadrant(x1, y1);
// call findQuadrant(point2)
Q2 = findQuadrant(x2, y2);
// output results
System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")");
System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n");
System.out.printf("The distance between the two points
is: %-8.2f%n", dist );
System.out.println("Point 1 is in " + Q1);
System.out.println("Point 2 is in " + Q2);
} // end main()
/****************************************************
************************/
Figure 12 – a program
organized as 3 methods
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 19
// this method calculates and returns the distance between
two points
public static double calcDistance(double x1,double
y1,double x2,double y2) {
double deltaX; // difference in x coordinates
double deltaY; // difference in x coordinates
double dist; // distance between (x1,y1) and (x2,y2)
deltaX = (x1-x2);
deltaY = (y1-y2);
dist = Math.hypot(deltaX, deltaY);
return dist;
/* this whole method could be one line:
* return Math.hypot( (x1-x2), (y1-y2) );
*/
} // end calcDistance() {
/****************************************************
************************/
// this method returns the quadrant that contains the point
public static String findQuadrant(double x,double y) {
String Q; //quadrant message
if ( (x >= 0.0) && (y >= 0.0) )
Q = "Quadrant I";
else if ( (x < 0.0 ) && ( y >= 0.0) )
Q = "Quadrant II";
else if ( (x < 0) && (y < 0.0) )
Q ="Quadrant III";
else // ( (x >= 0) && (y < 0.0) )
Q = "Quadrant IV";
return Q;
} // end findQuadrant
} // end class
Here is sample output from the program:
Enter the x coordinate of point 1 :3
Enter the y coordinate of point 1 :4
Enter the x coordinate of point 2 :-3
Enter the y coordinate of point 2 :-4
Point 1 is (3.0,4.0)
Point 2 is (-3.0,-4.0)
The distance between the two points is: 10.00
Point 1 is in Quadrant I
Point 2 is in Quadrant III
The code in Figure 13 on the next page contains an alternative
version of the same program as Figure
12. To the user, the two programs look the same. They have
identical input and output. They are in the
Week 5 Canvas files. These two Java applications are the
topic of the Week 5 class discussion.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 20
/* distance between two points - alternative programming style
* CSCI 111 Spring 2015 last edited Sept 24, 2013 by C.
Herbert
*/
package twopointsb;
import java.util.Scanner;
public class TwoPointsB {
// The main method calls a methods to calculate the distance
between
// two points, then prints that distance and the quadrant of
each point
public static void main(String[] args) {
double x1,y1,x2,y2;
double dist;
// input coordinates
x1 = inCor("x", "1");
y1 = inCor("y", "1");
x2 = inCor("x", "2");
y2 = inCor("y", "2");
dist = Math.hypot( (x1-x2), (y1-y2) );
System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")");
System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n");
System.out.printf("The distance between the two points
is: %-8.2f%n", dist );
printQuadrant("1", x1 , y1);
printQuadrant("2", x2 , y2);
} // end main()
/****************************************************
************************/
// this method gets as input a single coordinate of a point
public static double inCor(String axis, String point) {
// set up instance of Scanner for input
Scanner kb = new Scanner(System.in);
// get coordinate with prompt
System.out.print("Enter the " + axis + " coordinate of point
" + point + " :");
return kb.nextDouble();
} // end inCor()
/****************************************************
************************/
// this method prints the quadrant a point is in
public static void printQuadrant(String P, double x,double y)
{
if ( (x >= 0.0) && (y >= 0.00) )
System.out.println( "Point "+ P + " is in Quadrant I");
else if ( (x < 0.0 ) && ( y >= 0) )
System.out.println( "Point "+ P + " is in Quadrant II");
else if ( (x < 0) && (y < 0) )
System.out.println( "Point "+ P + " is in Quadrant III");
else // ( (x >= 0) && (y < 0) )
System.out.println( "Point "+ P + " is in Quadrant IV");
} // end printQuadrant
} // end class
Figure 13 –Figure 12’s
program reorganized.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 21
Key Terms
access modifier, 4
entry conditions, 10
exit conditions, 10
formal parameters, 7
inline methods, 6
leaf nodes, 15
method declaration, 4
method header, 4
method modifiers, 4
modular development, 16
organizational chart, 14
parameter passing by value, 8
private access, 4
protected access, 4
public access, 4
return type, 6
reusable code, 16
static method, 6
throws, 4
top-down design, 14
void, 6
Chapter Questions
1. So far this semester we have only created one method at a
time in our applications, but what are some
examples of methods from other classes that we have invoked in
our source code?
2. What is included in a method declaration?
3. What are the parts of a method header?
4. What is in the parentheses that follow the name of the method
in a method header? What does it
mean if the parentheses are blank?
5. What does it mean if the word throws follows a method
header?
6. Where does the return type belong in a method header?
7. What are the three access modifiers used in Java? What does
the private access modifier do?
8. When do we need a main method in a class? What modifiers
should be used with this method?
9. What does the JLS tell us about a method with the modifier
static? How is a static method invoked?
10. What methods that we have previously used were static
methods? What methods that we have
previously used were associated with an instance of a class?
11. What do we call a method that does not return as value?
What return type does it have?
12. Where can we use a method that returns a double value?
13. What is a method that can be invoked in a Java expression
often called?
14. What is the difference between the formal parameter list and
the actual parameters? Which of the two
declares new variables for a method? Which contains values
used to initialize variables?
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 22
15. What should be included in a comment describing each
method? What happens to this documentation
when a method is compiled?
16. What should be described as part of a method’s entry
conditions? What should be described as part of a
method’s exit conditions?
17. In what two ways can a method be invoked from another
method? How is a value returning method
invoked? How is a void method invoked?
18. How are parameters passed in Java? How must the values of
the actual parameters be organized when a
method is invoked?
19. When breaking a method down into parts using top-down
design, which nodes on an organizational
chart need to be developed and then recombined to create the
overall solution to the original problem?
20. What are five of the ways in which modular development
facilitates production of computer software?
Chapter Exercises
1. Match the actual parameters on the left with the correct
formal parameter list on the right.
(3,4)
(2.0,3.0)
(“Jones”, 97.5)
(“J00123453”, “B”)
(42, 10.50)
(double hours, double rate)
(String name, double pay)
(short people, double PoundsOfCake)
(String Jnumber, String grade)
(int length, int width)
2. Multiplication Table
A set of nested for loops can be used to print a multiplication
table using System.out.printf statements.
1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5 10 15 20 25 30 35 40 45
6 6 12 18 24 30 36 42 48 54
7 7 14 21 28 35 42 49 56 63
8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
Write a program to print such a multiplication table, using a
method to print each row, which is invoked
from the method that prints the overall multiplication table.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 23
3. Printing Patterns
Nested for loops can print patterns of stars, such as the example
below:
for(i=1; i<=5; i++)
{
for(j=1; j<=10; j++)
{
System.out.print(“*”);
} // end for j
System.out.println();
} // end for i
Output from this program:
**********
**********
**********
**********
**********
Write a program with a main method which asks the user for the
number of rows and for the number of
columns, then calls a method which uses that information to
print a rectangle of stars.
4. Celsius to Fahrenheit Table
Write a program to print a Celsius to Fahrenheit conversion
table that invokes a method to calculate
Fahrenheit temperature using formula is F = ( 9.0
5.0
C) + 32.0. The main method should have a loop to
print the table, calling the conversion method from within the
loop.
The table should include integer Celsius degrees from 0 to 40.
You program does not need to use
integers, but the table should display the Celsius temperature,
then the Fahrenheit accurate to one-
tenth of a degree. The first few entries from the table are
shown below:
Celsius Fahrenheit
0 32.0
1 33.8
2 35.6
3 37.4
5. We wish to write a modular program that can be used to
calculate monthly payments on a car loan. The
formula is: payment =
������ ����∗ ������
1−(1+������ ����)−����ℎ�
The program will be composed of several methods – a main
method, a monthly interest rate method, a
monthly payment method, and an output method.
The main method should:
1. ask the user for
- the loan amount
- the annual interest rate ( as a decimal, 7.5% is 0.075 )
- the number of months
2. call a method to calculate and return the monthly payment
(Note: The formula uses monthly rate. Annual rate is input.
monthly rate = annual rate/12)
3. call a method to print a loan statement showing the amount
borrowed, the annual interest
rate, the number of months, and the monthly payment
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 24
6. International Gymnastics Scoring
We wish to write a program to quickly calculate gymnastics
scores for an international competition. Six
judges are judging the competition, numbered 1 through 6 for
anonymity. The program should have a
loop that:
1. calls a method asking for the score from a single judge, The
method should print the judge
number and score and return the judges score
2. adds the returned score to a total score.
After the loop is done, your program should call a method that
calculates and displays the average
score.
Scores are in the range 0 to 10 with one decimal place, such as
8.5. The average should be displayed
with two decimal places.
Here is a sample of the output:
Score for Judge 1: 8.5
Score for Judge 2: 8.7
Score for Judge 3: 8.4
Score for Judge 4: 9.1
Score for Judge 5: 8.9
Score for Judge 6: 9.0
The average score is: 8.77
7. Test for Divisibility
If the remainder from dividing A by B is zero, then A is a
multiple of B ( A is evenly divisible by B ).
For example, the remainder from dividing 6, 9, or 12 by 3 is 0,
which means 6, 9, and 12 are all multiples
of 3.
Write a program with a loop to to print the numbers from 1 to
25, and within the loop, invokes a
method to see if the number is a multiple of 2, a method to see
if the number is a multiple of 3, and a
method to see if the number is a multiple of 5. The methods
should each print a message if the number
is a multiple of the value for which they are testing.
Here is a sample of part of the output:
1
2 multiple of 2
3 multiple of 3
4 multiple of 2
5 multiple of 5
6 multiple of 2 multiple of 3
7
8 multiple of 2
9 multiple of 3
10 multiple of 2 multiple of 5
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 25
8. Estimate of a Definite Integral
Write the program to estimate a definite integral with
rectangles, with a loop that calls a method to
calculate the height and area of each rectangle.
A loop in a computer program can be used to approximate the
value of a definite integral. We can
break the integral into rectangles, find the area of each
rectangle then add the areas together to get the
total area, as shown in the accompanying diagram. In practice,
we could make the width small enough
to achieved the desired accuracy in estimating the area under
the curve.
y = 9-x2
area under the curve
estimated by rectangles
As the width of the rectangles gets progressively smaller, their
total area gets closer to the total area
under the curve. This is an old method that predates Calculus.
Both Leibnitz and Newton used this
method, eventually developing calculus from the concept of
infinitesimals, which, in the case of our
rectangles, would amount to asking, what would the total area
be if we had very many rectangles with
very small width?
This was tedious by hand, but we now have computers. We can
set the width of the rectangle. The
height of the rectangle is the y value at point x. So for example,
if we need to solve:
∫ 9 − �2 ��
−3
+3
The starting point is -3, the ending point is +3, and the height of
the rectangle at each value of x in
between the two is 9 − �2 ; Y at each x is the is the height of
the rectangle at that x. We can use a width
of 0.001, and write a loop like this:
for x = -3 to +3 step 0.0001 // x is -3.00, then -2.9, then -2.8,
etc.
{
y = 9 − �2 ; // the height is the y value at each x
area = y * .01; // the width is the increment, in this case 0.1
totalArea = totalArea + area;
}
In this version of the program, the statements in the box above
should be in a separate method, invoked
from within the loop. When the loop is finished, totalArea is
the total area of the rectangles, which is
an approximation of the area under the curve.
Your lab report should explain what you did, and the result of
your work.
JLK Chapter 5 – Methods and Modularity DRAFT January 2015
Edition pg. 26
9. Supermarket Checkout
Design a program for a terminal in a checkout line at a
supermarket. What are the tasks that are
included as part of checking out at a register? We must consider
things like the cost of each item,
weighing produce and looking up produce codes, the total cost
of the order, bonus card discounts, and
sales tax on taxable items only. You do not need to write the
program, but you should design the
methods using top down development and modular design.
Submit a description of the methods
needed for the program, a brief description of what each method
does, and a description of how the
methods are related to one another in terms of parameter
passing and return types.
10. We wish to write a program to draw the scene below. We
can create methods to draw primitive shapes,
as follows:
circle() takes x and y coordinates of center point, the radius,
and the color
triangle() takes x and y coordinates of each of three endpoints
and the color
rectangle() takes x and y coordinates of each of four corner
points and the color
Create a modular design for software to draw the scene using
the methods above. The software should
be layered. For example, a house() method should use the
primitive graphics methods to draw the
house.
Your design document should list and briefly describe each
method, including and what it does,
parameters, and any methods the method calls. Your list should
start with the main method.
— End of Chapter 5 —
The Java Learning Kit: Chapter 6 – Arrays
Copyright 2015 by C. Herbert, all rights reserved.
Last edited January, 2015 by C. Herbert
This document is a chapter from a draft of the Java Learning
Kit, written by Charles Herbert, with editorial input from Craig
Nelson, Christopher Quinones, Matthew Staley, and Daphne
Herbert. It is available free of charge for students in Computer
Science courses at Community College of Philadelphia during
the Spring 2015 semester.
This material is protected by United States and international
copyright law and may not be reproduced, distributed,
transmitted, displayed, published or broadcast without the prior
written permission of the copyright holder. You may not alter
or remove any trademark, copyright or other notice from copies
of the material.
The Java Learning Kit:
Chapter 6
Arrays
Lesson 6.1 – Arrays
Lesson 6.2 – One Dimensional Arrays in Java
Lesson 6.3 – Operations on Numeric Arrays
Lesson 6.4 – Searching and Sorting Arrays
Lesson 6.5 – Text File Input and Output in Java
Lab 6 – Programming Example: Moving Data between Arrays
and Files
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 2
Contents
Chapter 6 Learning Outcomes
...............................................................................................
..................... 3
Arrays
...............................................................................................
............................... 4
Array Storage in Computer Memory
...............................................................................................
.... 5
CheckPoint 6.1
...............................................................................................
..................................... 6
One Dimensional Arrays in Java
...................................................................................... 7
What is actually in an array in Java?
...............................................................................................
.... 7
Assigning Values to Array Elements
...............................................................................................
... 10
The Array length Property; Iterating an Array
................................................................................... 11
The Enhanced for Statement
...............................................................................................
............. 12
Copying an Array
...............................................................................................
................................ 13
Arrays as Method Parameters in Java
...............................................................................................
13
Passing an Array Element as a Method Parameter
........................................................................... 15
CheckPoint 6.2
...............................................................................................
................................... 15
Operations on Numeric Arrays
...................................................................................... 16
Sum, Average, and Count of Values in an Array
................................................................................ 16
The Minimum and Maximum Values in an Array
.............................................................................. 17
Searching and Sorting Arrays
........................................................................................ 18
Comparing Strings
...............................................................................................
.............................. 18
Linear Search of an Array
...............................................................................................
................... 18
Sorting an Array
............................................................................................ ...
................................. 21
Swapping the Values of Two Variables
.............................................................................................
22
CheckPoint 6.4
...............................................................................................
................................... 24
Text File Input and Output in Java
................................................................................. 25
Handling Data File Exceptions like Hot Potatoes
............................................................................... 26
A Technique for Writing Text Data Files using Java
........................................................................... 27
A Technique for Reading Text Data Files using Java
.......................................................................... 28
CheckPoint 6.5
...............................................................................................
................................... 29
Lab 6 – Programming Example: Moving Data between Arrays
and Files ............................................. 30
Key Terms
...............................................................................................
.............................................. 35
Chapter Questions
...............................................................................................
................................. 36
Chapter Exercises
............................................................................................ ...
................................... 37
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 3
The Java Learning Kit: Chapter 6
Arrays
This chapter introduces the concept of an array and working
with arrays in Java, along with the use
of text files in Java applications for long-term storage of arrays
and other data.
Lesson 1 introduces the concept of an array as a set of
subscripted variables, including a look at
how arrays are stored in memory.
Lesson 2 shows how to implement arrays for Java’s built-in data
types.
Lesson 3 discusses simple statistical processing of numeric
arrays — finding the sum, average
minimum, and maximum in an array of numbers.
Lesson 4 looks at simple techniques for searching and sorting
arrays.
Lesson 5 introduces simple text file I/O in Java.
Chapter 6 Learning Outcomes
Upon completion of this chapter students should be able to:
stored in a
computer’s memory.
an array in Java; and how to declare an
array, initialize
an array, and iterate an array in Java.
parameter in Java;
and how to pass an individual array element as a method
parameter in Java.
iterate an array;
and pass both references to arrays and individual array elements
as
parameters.
operations on
numeric arrays, including counting array elements, and finding
the sum,
average, minimum and maximum of values in an array.
sum, average,
minimum and maximum of values in an array.
algorithm for a linear to search of an array.
two variables,
search an array, and sort an array.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 4
Arrays
Until now we have been using single variables in our Java
programs. Java, like most other programming
languages, Java also supports arrays. An array is a set of
indexed variables, all of the same data type.
Instead of just having individual variables such as x, y, or
empName, we can have a set of indexed
variables such as x1, x2, x3, … and so on, where the value of
the index identifies an element of an array.
Each element of an array is an individual data item in the array,
such as:
empName0, empName1, empName2, … empNamen-1
In mathematics, such an array is also referred to as a set of
subscripted variables, because the index is
written as a subscript. In Java, they may also be called
subscripted variables, but instead of using
subscripts, Java uses square brackets following the variable
name to indicate an array or an element in
an array. empName0, empName1, employname2… from
mathematics would be written as empName[0] ,
empName[1], empName [2] … empName [n-1] in Java.
empName is the name of the array; whereas
empName[i], where i is an integer, is an element in the array
empName. The index values in an array
start at zero for reasons we will see later in this chapter.
empName[0] , empName[1], empName[2] … empName[n-1]
Arrays are very useful for storing and working with sets of
similar data items, such as lists of test scores.
We will see how to set up an array to hold a set of numbers,
such as test scores, then write code to find
the sum, the average, the minimum or the maximum of the
numbers. Once data has been established in
the computer’s memory as an array, we can do many things with
the data, including conducting a full
statistical analysis of the data, searching the data for specific
items, or sorting the data. Later, when we
learn to work with objects, we can set up an array of objects,
such an array of student records with
properties like student number, first name, last name, address,
and major, then we can sort or search
through the data according to any of the object’s properties.
But for now, we will only work with arrays
of primitive data types and Strings.
Most high-level programming languages support using arrays of
data. They generally have two different
type of arrays, single-dimensional arrays and mutli-dimensional
arrays. A single dimensional array, also
called a linear array, is an array with only one index variable,
forming what can be thought of as a line of
data items. The above example of empName[0] , empName[1],
empName [2] … empName [n-1] is a one
dimensional linear array.
Multi-dimensional arrays have multiple index variables, such as
the two-dimensional array shown here:
a0,0 a0,1 a0,2 . . . a0,n
a1,0 a1,1 a1,2 . . . a1,n
a2,0 a2,1 a2,2 . . . a2,n
am,0 am,1 am,2 . . . am,n
This is a two dimensional array from the world of mathematics,
forming a table with m rows and n
columns. In Java, the array would look like this:
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 5
a[0,0] a[0,1] a[0,2 ]. . . a[0,n]
a[1,0] a[1,1] a[1,2 ]. . . a[1,n]
a[2,0] a[2,1] a[2,2 ]. . . a[2,n]
a[m,0] a[m,1] a[m,2] . . . a[m,n]
Two dimensional arrays can be used to represent tables of data
with rows and columns of information,
similar to an electronic spreadsheet. They are often used for
matrices in linear algebra problems.
Multi-dimensional arrays can have more than two dimensions.
A three dimensional array could, for
example, represent a three-dimensional matrix for solving
problems related to three-dimensional
Euclidean space with x, y, and z coordinates. However, for the
remainder of this chapter we will stick
with simple single dimensional arrays, leaving the more
complex problems for another day.
Array Storage in Computer Memory
The values for variables in a computer program are stored in a
computer’s internal memory while the
program runs. Hence, each variable name is associated with a
specific address in the computer’s
memory. This matching of variables to memory addresses is
usually managed by the computer’s
operating system with a symbol table. A symbol table is a list
of symbolic names, such as the names of
methods, classes, and variables, mapped to specific addresses in
a computer’s internal memory.
Almost all modern computer systems have byte addressable
memory, meaning that bytes in a
computer’s memory are sequentially numbered, regardless of
the word length of a particular processing
unit. There are many advantages to this, which are discussed in
computer architecture and organization
courses such as CSCI 213– Computer Organization at
Community College of Philadelphia.
The following example shows how an operating system keeps
track of the values of variables using a
symbol table. The memory map shows us how space is allocated
in the computer’s memory.
variables symbol table memory map
int score; score 4000 4000 score
double velocity; velocity 4004 4001
int colorDepth; colorDepth 400C 4002
boolean transparent; transparent 4010 4003
4004 velocity
4005
Memory is allocated according to how variables are declared.
4006
Space is allocated based on data types, as described back in
chapter 2, for example:
int 32 bits (4 bytes)
double 64 bits (8 bytes)
boolean (1 byte in this system)
The symbol table records where variables are stored
in the internal memory. Memory addresses are hexadecimal
(base 16).
4007
4008
4009
400A
400B
400C color depth
400D
400E
400F
4010 transparent
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 6
When an array is declared, the operating system only keeps
track of array’s base address, which is the
location where the array starts in memory. Here is an example:
CheckPoint 6.1
1. What is the relationship among the terms array, indexed
variables, and subscripted variables?
2. What is a linear array?
3. What does it mean to say that most computers use byte-
addressable memory?
4. If array begins at memory address 5000 and each array
element requires 16 bits of storage
space, where will the array element with index 3 be stored in
memory?
5. How can arrays be used to represent tables of data with rows
and columns, similar to an
electronic spreadsheet?
variables symbol table memory map
priority = new int [6]; priority 4000 4000 priority [0]
int score; score 4018 4001
4002
The symbol table only contains the base address of an
array. Since all of the elements of the array are the
same data type, they will all use the same number of
bytes in memory. So, the computer calculates the
address of an element in an array using the formula:
memory address = base address + (index * size)
In this example, the base address for the array priority
is 4000. The size of each element is 4 bytes, since it is
an array of integers. So, the address of priority[2] is:
address of priority[2] = 4000 + 2 * 4
which equals 4008.
(Remember, addresses are base 16 – hexadecimal).
This scheme works because the index of the first
element in the array is 0, not 1. In fact, this is why
array index values start at 0.
Notice that the highest index is one less than the size of
the array, because the array index numbering starts at
zero. In this example priority has 6 elements,
priority[0] through priority[5].
4003
4004 priority [1]
4005
4006
4007
4008 priority [2]
4009
400A
400B
400C priority [3]
400D
400E
400F
4010 priority [4]
4011
4012
4013
4014 priority [5]
4015
4016
4017
4018 score
4019
401A
401B
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 7
One Dimensional Arrays in Java
A one-dimensional array in Java is a indexed fixed-length
homogeneous data structure. In other words,
it is a set of sequentially numbered data elements, in which all
of the data must be of the same data
type, and with a number of elements that cannot be changed. In
Java, an array is an object.
There are two parts to declaring an array in Java, unlike
primitive data types, which have a one-step
declaration. First, the array must be named; second, the size
must be declared.
step 1 – Declare a name for the array. There are two styles for
doing this, which both assign a name to
an array, but do not create the array in memory: (The first style
is preferred.)
int[] score; // declares score to be the name of an int array, it
has no elements
int score[]; // declares score to be the name of an int array, it
has no elements
step 2 – Declare the size of the array.
score = new int[10]; // declares the array score to have 10
integer elements
The number in brackets is the number of elements or size of the
array, also known as the array length.
The indexes in Java arrays must be non-negative and always
start at zero. The highest index will be one
less than the size of the array. If the array length is n, then the
highest index will be n-1.
The statement that declares the array length actually creates the
array.
The two statements naming an array and declaring an array must
both be used to create the array:
int[] score;
score = new int[10];
The name and size declarations for an array can be put together
in one Java statement, which is the
easiest and most common way to create an array in Java:
int[] score = new int[10]; // score is the name of an integer
array with 10 elements
The keyword new is necessary when declaring objects. An
array is an object in Java. This statement
declares an array named score and sets the size to 10 elements.
What is actually in an array in Java?
Each element in an array is an individual variable of the data
type declared for the array. For example, if
empName is declared as:
String[] empName = new String[10];
then each of the array elements, such as empName[3], is a
String variable.
If the data type of an array is a primitive data type, then each
element of the array contains a value of
that data type. If the data type of an array is a class of objects,
then each element in the array contains
a memory address referring to where an object of the correct
data type is stored in memory. A memory
address referring to where an object is stored is called a
reference to an object. Java Strings are objects,
so each element in a String array holds a reference to a String,
not the String itself.
Example 1 – an integer array
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 8
An array of integers contains the actual values of integers, since
int is a primitive data type.
int[] score = new int[5];
This statement creates an array of integers named score with 5
elements. The actual values of integers
would be stored in the each element in the array, such as:
memory
address
variable name for
this address
value stored
at this address
4000 score[0] 93
4004 score[1] 87
4008 score[2] 91
400C score[3] 95
4010 score[4] 88
We can think of an array as a set of empty boxes. In the integer
array score, each box holds an integer:
Score[]
93 87 91 95 88
Example 2 – A String array
With any array of objects, including a String array, the elements
of the array actually contain references
to the objects, not the objects themselves. So, an array of
Strings would contain references to where
the Strings themselves are stored in memory, like this:
String[] empName = new String[5];
memory
address
variable name for
this address
value stored
at this address
4000 empName[0] ….4184
4004 empName[1] ….4210
4008 empName[2] ….4258
400C empName[3] ….510C
4010 empName[4] ….4412
This example assumes that each memory address is 32 bits (4
bytes)
long, but only the last 4 hexadecimal digits are shown.
The Strings are actually stored in the memory locations
referenced by the values in the array.
If we think of an array as a set of empty boxes, then each box in
the String array empName, holds a
reference to where a String value is actually stored in memory:
empName[]
….4184 ….4210 ….4258 ….510C ….4412
“Jones” “Goldschneider” “Brown” (and so on…)
Why does Java store arrays of objects this way? Remember, an
array is a fixed length data structure, but
Strings and many other objects are not fixed length, their sizes
can change. This method for storing
objects in memory allows variable length objects to be store in
fixed length arrays. It also has several
advantages that are beyond the scope of what we cover in this
chapter.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 9
Even though the elements of a String array actually contain
references to Strings, if we use a variable
from the array in our Java code, we will get the String, not the
reference. For the example above:
System.out.println( empName[2] ); //prints the name Brown,
not the reference ….4258
Once we learn to work with objects, we will see that we can
have an array for any type of object, just as
with Strings, using references to the objects stored in memory,
such as an array of images:
Example 3 – an Array of Images
JPGimage[] orientation = new JPGimage[5];
orientation[]
4100 6404 7820 880C B204
… and so on. Each element in the array contains a reference
to a stored image.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 10
Assigning Values to Array Elements
There are two ways to assign values to array elements:
1. using assignment statements
For example:
score[3] = 98; // an int value is assigned to the fourth
element in score
empName[0] = “Jones”; // a String value is assigned to
the first element in empName
a[4] = x; // a[4] is set to the value of x (data types
must match)
2. by listing values in an alternate array declaration
Arrays may be declared in a statement that lists their values:
int[] score = {93, 87, 91, 95, 88};
This method is sometimes called an explicit array declaration.
The values listed in braces,
separated by commas, are assigned in order to the array
elements. The length of the array is
determined by the number of values in the list. The keyword
new is not needed in an explicit
array declaration.
An explicit array declaration like the one just shown above
works well for small arrays, but can be
awkward for large arrays.
One common way to initialize the values in an array is with a
count controlled loop. Here are a few
examples:
Example 4 – Initializing all of the elements in an Array to Zero
The following code initializes the values of an array of data
type double all to the same value, zero:
double[] cost = new double[100]; // an array of 100 numbers
for(int i=0; i<100; i++)
cost[i] = 0.0;
Example 5 – Initializing an Array with User Input
The following code initializes the values of an array of data
type String with user input. Inside the array
the names are numbered starting with 0, but to the user they are
numbered starting with 1. This
assumes that the code is encapsulated, meaning that the user
does not see the code.
String[] student = new String[10]; // an array of 10 student
names
for( int i= 0; i < 10; i++)
{
// Ask the user for a student name, then get the name from the
keyboard
System.out.print("Please enter the name of student number"
+ (i+1) + “:” );
student[i] = x.nextLine();
} // end for
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 11
Example 6 – Initializing an Array with random numbers
The following code initializes the values of an int array with
random numbers between 1 and 100. An
array of random numbers is often used in game or simulation
programming, or to test other software.
int [] num = new int[100]; // an array of 100 integers
for( int i= 0; i < 100; i++)
num[i] = 1+(int)(Math.random()*100); // random, 1 <= num[i]
<= 100
Math.random() yields a value between 0 and 1; the arithmetic
converts it to a integer between 1 and 100.
The Array length Property; Iterating an Array
x.length, where x is the name of an array, is a method for
instances of array objects that returns the
length of the array as an integer. For example, if the array
score[] has 10 elements, then score.length
returns the value 10.
The length property can be used to iterate an array. To iterate an
array means to go through each of the
elements in the array on at a time. The three examples above
each iterate an array, and could be
written to use the length property. Here is the code from
example 4, above, re-written using the length
property for the cost array.
Example 7 – Initializing an Array using the length method
double[] cost = new double[100]; // an array of 100 numbers
for(int i = 0; i < cost.length; i++)
cost[i] = 0.0;
There are many different reasons to iterate an array – to
initialize the array as above, or to print the
elements of the array, for example.
Example 8 – Printing the Elements of an Array
// the following assumes student is a String array that has
been initialized
for( int i= 0; i < student.length; i++)
System.out.print("Student number " + ( i+1) + “ is ” +
student[i]);
Example 9 – Printing the Fibonacci numbers
The Fibonacci sequence is a sequence of numbers that starts
with 0 and 1, then each successive term in
the sequence determined by adding the previous two terms.
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
…
Such a pattern is very common in the natural world. The
following diagrams help us to understand why
that is so. On the left, we see a set of rectangles composed by
adding squares whose sides are
successively larger Fibonacci numbers. The next square to be
added will have a side of length 13, and
will be added above the existing rectangle. On the right we see
a spiral drawn by connecting the corners
of Fibonacci squares. The growth of branches on a tree, the
shape of a spiral sea shell, the pattern of
seeds on a sunflower, the growth of a population of rabbits, and
many other patterns in the real world
fit the Fibonacci sequence.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 12
In this example, we will store the first 10 Fibonacci numbers in
an array named fib[], then print the
array. We will declare the array using a set of values.
int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with
Fibonacci numbers
int i;// used as an array index
System.out.println(“The first ten Fibonacci numbers” );
// this loop prints the values in the array
for( i= 0; i < fib.length; i++)
System.out.print(fib[i] + “ “);
System.out.println(); // go to a newline after printing the array
values
The output looks like this:
The first ten Fibonacci numbers
0 1 1 2 3 4 5 8 13 21 34
The Enhanced for Statement
The for statement we have been using so far is the basic for
statement. Java also has a special version of
the for statement, called the enhanced for statement. The
enhanced for statement iterates an entire
array. It may only be used with an array or an object that can be
iterated like an array.
The enhanced for statement has a loop header with the keyword
for, followed by parentheses that
contain an integer declaration and the name of an array. The
statement or block of code following the
loop header will be executed once for each element in the array.
Within the statement or block of code, the integer declared in
the loop header refers to each element in
the array. The syntax within an enhanced for loop can be
tricky, so be careful. We do not use the name
of the array within the loop, only the integer variable declared
in the header. This variable refers to an
element of the array, sequentially incremented each time
through the loop. Here is the syntax of the
enhanced for loop:
for ( integer declaration : name of an array)
block of code
Here is the same code from above to print the array with the
first 10 Fibonacci numbers, using an
enhanced for loop instead of a basic for loop:
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 13
Example 10 – the enhanced for loop
int[] fib = {0,1,1,2,3,5,8,13,21,34} // an array initialized with
Fibonacci numbers
System.out.println(“The first ten Fibonacci numbers” );
// this loop prints the values in the array using the enhanced for
statement
for(int i : fib)
System.out.print(i + “ “); // i refers to fib[i] in this enhanced
for loop
System.out.println(); // go to a newline after printing the array
values
The output looks like this:
The first ten Fibonacci numbers
0 1 1 2 3 4 5 8 13 21 34
Although it is convenient, the enhanced for loop has limited
applications. It can only be used to iterate
an entire array, not part of an array, and the declared integer
variable cannot be used as an integer
variable within the loop, only to refer to each element of the
array.
Copying an Array
An assignment statement such as second = first; will not copy
an array; it copies the reference to the
array, creating two variables referencing the same array. To
copy an array in Java, we must create
another array of the same data type and size, then copy each
value from the original array into the new
array. The actual copying can be done with a for loop or with
an enhanced for loop.
Example 11 – copying an array
// an array initialized with ten prime numbers
int[] first = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
// To copy an array, we need to create another array of the
same data type and size.
int[] second = new int[10];
// Then, we copy each element from the first array into the
second array.
for(int i : i < first.length; i++)
second[i] = first[i];
// This could also be done with an enhanced for loop
for(int i : first)
second[i] = first[i];
Arrays as Method Parameters in Java
An entire array can be passed as a method parameter, but
remember, the name of the array by itself is a
reference to the base address where the array is stored in
memory. It is this reference, and not the
values in the array, that is passed to another method when an
array is passed in Java. We end up with
two different reference variables pointing to the same array in
memory, not two different arrays, as
shown in example 12 on the next page.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 14
Example 12 – Passing an Array as a Parameter
In this example, an entire array is passed from the main method
to the method printJob(). However, the
array is not really passed; it is the value of the reference
variable that points to the array’s location in
memory that is really passed. Java always passes values. In this
case the value is the address of the array
in memory, so we end up with two different variables, priority –
the original name for the array – and
category – the copied name – both referring to the original
array.
variables symbol table memory map
priority = new int [6]; priority 4000 4000 priority [0]
int score; score 4018 4001
. . . 4002
int[] category; category 4000 4003
int i; i 4054 4004 priority [1]
int[] priority = new int[6];
. . .
// call method printJob()
printJob(priority);
. . .
public static void printJob(int[] category){
for( int i=0; i < category.length; i++) {
System.out.printl(“Job” + i + “is in category “ + category[i]);
. . .
}
The method header for the printJob() method establishes a
reference variable to
refer to an array, category, but category has no value until the
method is invoked
from another method.
When printJob() is invoked from the main method, the value of
the array reference
variable priority is passed to array reference variable category
in the formal
parameter list. Now both priority and category have the same
value, the address
of the same array. This means they refer to the same array –
priority and category
have become two names for the same array – whatever we do to
one we do to the
other. If we change the value of an element in category we also
change the value
of that element in priority. category[3], for example, is
priority[3].
Java always passes a value, not a reference to a value, but that
value may be an
address of an object, such as the address of the array passed in
this case.
4005
4006
4007
4008 priority [2]
4009
400A
400B
400C priority [3]
400D
400E
400F
4010 priority [4]
4011
4012
4013
4014 priority [5]
4015
4016
4017
4018 score
4019
401A
401B
401C
401D
401E
401F
4020
The value of the actual
parameter priority is passed
to the formal parameter
category, but that value is a
reference to an array.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 15
Passing an Array Element as a Method Parameter
Each element in an array is an individual variable that is treated
like any other any variable with the
element’s data type. It may be used like any other variable of
that data type, including as an actual
parameter for a method.
Example 13 – passing an array element as a parameter
In this example, price[] is an array of double values. price[3] in
the main method is used as an actual
parameter. The value of the variable price[3] is passed to the
formal parameter cost when the
method is invoked.
double[] price = { 1.99, 3.87, 4.95, 2.99, 2.57};
. . . // all of the code is not shown
currentSale(price[3]);
. . . // all of the code is not shown
/****************************************************
******************/
public static void currentSale(double cost) {
System.out.printl(The cost of the item is: “ + cost);
. . . // all of the code is not shown
}
The value of price[3] is copied to cost in the method
currentSale(). Any change that is later made to
cost has no effect on the original value in price[3].
CheckPoint 6.2
1. A one-dimensional array in Java is defined as an indexed
fixed-length homogeneous data
structure. What does this mean?
2. What is actually in an array if the array’s data type is a
primitive data type and how does this
differ from what is in an array if the array’s data type is class of
objects?
3. What are the two ways that a value can be assigned to an
array element?
4. Create an example showing how the enhanced for statement
can be used to iterate an array.
5. How is an entire array passed as a method parameter and
what happens in the original array if a
value is changed in an array within a method that has received
the array as a parameter?
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 16
Operations on Numeric Arrays
Once we have a set of numbers stored in an array, we can
perform numerical analysis of the data.
Common operations on numerical arrays include finding the
sum, the average, the minimum and the
maximum of the values in an array.
The following examples show how to do each of these things for
a set of values in a double array.
Sum, Average, and Count of Values in an Array
To find the sum of a set numbers in an array we need a variable
to hold the sum. It should have the
same data type as the elements of the array, and it should be
initialized to zero. Then, we iterate the
loop, adding each value in the array to the sum, as in the
following code. After the loop to iterate the
array is finished, then the variable will hold the sum.
The average is simply the sum divided by the number of
elements in the array. The array length
property is the number of elements in the array.
Example 14 – finding the sum and average of values in an array
double[] cost = new double[100]; // an array of 100 numbers
double sum = 0;
// the statements that give values to the elements in the array are
not shown
for(int i= 0; i < cost.length ; i++)
sum = sum + cost[i];
System.out.println("the total cost is " + sum);
System.out.println( "the average cost is " + sum/cost.length );
In this example, the average is calculated as part of the print
statement. We could also have a variable
to hold the average if we need to use it later.
Counting Elements in an Array
Sometimes we wish to count all of the values in an array that
meet a certain condition. To do so, we
simply initialize a counter to zero, then increment the counter
for each element that meets the
condition.
Example 15 – counting the elements in an array
In this we will again use the first ten Fibonacci numbers.
Instead of printing each of the numbers, we
will only print the even Fibonacci numbers and we will count
them as well.
The variable countEven is first initialized to zero, then, as we
iterate the array, we will increment the
count for each even Fibonacci number. To test for even
numbers, we will use the Java’s remaindering
operation (%), which returns the remainder of an integer
division operation. If the remainder is zero
when we divide by two, then the number is an even number.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 17
int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with
Fibonacci numbers
int i;// used as an array index
int countEven = 0;// used to count how many of the first 10
Fibonacci numbers are even
System.out.println(“Even Fibonacci numbers” );
// this loop prints the values in the array
for( i= 0; i < fib.length ; i++)
if (fib[i] % 2 == 0) {
countEven++;
System.out.println( fib[i] + “ is even”);
}
System.out.println ( countEven + “ of the first 10 Fibonacci
numbers are even”);
The output looks like this:
Even Fibonacci numbers
0 is even
2 is even
8 is even
34 is even
4 of the first 10 Fibonacci numbers are even.
The Minimum and Maximum Values in an Array
To find the minimum value in an array, we start with a variable
to hold the minimum. We initialize the
minimum to the first value in the array, then go through the rest
of the values in the array, testing each
to see if it is less than the minimum. If a value is less than the
minimum, it becomes the new minimum.
After going through the entire array, the variable will hold the
minimum value from the array.
The maximum is calculated in almost the same way, setting the
first value to be the maximum, except
we then check to see if each value is greater than the maximum.
Example 16 – finding the minimum value in an array
double[] cost = new double[100]; // an array of 100 numbers
int i;
double minimum;
// the statements that give values to the elements in the array are
not shown
minimum = a[i];
for( i= 1; i < cost.length ; i++) // iterate starting at the second
element
if ( cost[i] > minimum )
minimum = cost[i];
System.out.println("the minimum cost is " + minimum);
Example 17 – finding the maximum value in an array
double[] cost = new double[100]; // an array of 100 numbers
int i;
double maximum;
// the statements that give values to the elements in the array are
not shown
maximum = a[i];
for( i= 1; i < cost.length ; i++) // iterate starting at the second
element
if ( cost[i] < maximum)
maximum = cost[i];
System.out.println("the maximum cost is " + maximum);
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 18
Searching and Sorting Arrays
Comparing Strings
In order to search or sort an array of Strings we need to be able
to compare String values. This is easy for
integers and floating point data, but when it comes to Strings,
there is a complication.
The Boolean condition (a == b) will work if a and b are Strings,
but it doesn’t work the way most people
think it does. Strings are objects, and a comparison of two
objects using the == operators compares the
reference values stored in the two variables, not the values of
the objects themselves. In other words,
(a==b) will be true only if a and b refer to the same object, not
equal objects. We have a similar
problem with the < and > operators.
Java has a number of different ways to compare objects in
general and Strings in particular. Here we
will look at two different methods from the String class that can
be used to compare Strings:
1. the a.matches(b) method. The String matches() method
returns a true value if the String
variable a is equal to the String expression b, otherwise, it
returns a false value. The String
expression may be a variable, a String literal, or anything that
evaluates to or returns a String.
2. the a.compareTo(b) method. The String compareTo() method
compares two Strings
lexicographically. A lexicographic comparison compares two
text items character-by-character
using a predefined collating sequence. In the case of Java
Strings, the collating sequence is the
UTF-16 version of Unicode. This is similar to the way a person
might compare two names to see
which one comes first alphabetically. The method returns an
integer value,
a. If the two Strings are the same, then the compareTo() method
returns the integer 0.
b. If a is less than b, then the method returns an integer less
than 0 (a negative integer).
c. If a is greater than b then the method returns an integer
greater than 0 (a positive
integer).
The String matches() method is an easy way to see if two
Strings are the same. The String compareTo()
method is useful for when we are trying to see which String
comes before the other, such as when we
are sorting a list of String values.
String handling is covered more in detail later in this course,
and in subsequent courses. The matches()
and compareTo() methods are used in the rest of this section.
Linear Search of an Array
Sometimes we wish to search an array to see if it contains a
certain value. We can do this many
different ways, but the simplest and most straightforward is a
linear search. In a linear search of an
array, we look at each value in the array one at a time to see if
the value we are seeking is in the array.
If we find the value, then we are done. If we get to the end of
the array without finding the value, then
the value is not in the array.
There are several different ways to implement a linear search.
We will use a loop with a compound
condition and a Boolean variable to keep track of whether or not
the value we are seeking is in the
array. In the following example, we first look at the
pseudocode for the array then see the final program
built from that pseudocode.
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 19
Example 18 – linear search of an array
In this example, an array contains a list of cities that have
professional football teams. The user enters
the name of a city to see if it is in the list. The program will
perform a linear search of the array. First, a
boolean variable named found is set to false. The continuation
condition in the for loop to iterate the
array will contain a compound condition, continuing while
found is false and while the end of the array
has not been reached. If the city is found, a message is printed
and a boolean variable is set to true to
terminate the loop. If the found variable is still false after the
loop, a not found message is printed.
Using the found variable in the compound condition provides an
advantage by making the search more
efficient. With it, the loop will stop as soon as the value is
found. Without it, the loop always goes
through the entire array. Consider, for example what happens
if the value being sought is in the first
element in an array of 100 elements. With the compound
condition, the loop stops after looking at the
first element. Without the compound condition the loop iterates
all 100 times.
The efficiency of algorithms is important, especially as data
sets grow larger. Algorithmic efficiency is
studied in detail CSCI 112 and 211.
Pseudocode for a linear search of a String array
/* in the search, n is the loop counter -- the continuation
condition is:
( n less than NFLcities.length )and (target city not found)
*/
String[] NFLcities; // an array holding the names of cities
with NFL teams
n int; // loop counter
boolean found = false; // will be set to true if the city is found
in the list
print intro message
get the target name of the city from the user
for ( i=0; not (found) AND n < NFLcities.length ; n++)
if ( target matches NFLcities[n] ) // if the name entered
matches this entry in the list.
print NFLcity[n] has an NFL team
set found to true
after the loop – if not(found) print “ [target] is not in the list of
cities with an NFL team.”
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 20
/* CSCI 111 - Fall 2013
* NFL City Search Program
* This program performs a linear search of a String array with
* the names of cities that have NFL teams
* last editied Sept. 28, 2013 by C. Herbert
*/
package nflcities;
import java.util.Scanner;
public class NFLcities {
public static void main(String[] args) {
// an array holding the names of cities with NFL teams.
String[] NFLcities = {"Buffalo", "Miami", "Boston", "New
York", "Baltimore",
"Cincinnati", "Cleveland", "Pittsburgh", "Houston",
"Indianapolis",
"Jacksonville", "Tennessee", "Denver", "Kansas City",
"Oakland",
"San Diego", "Dallas", "New York", "Philadelphia",
"Washington", "Chicago",
"Detroit", "Green Bay", "Minnesota", "Atlanta", "Charlotte",
"New Orleans",
"Tampa", "Arizona", "St. Louis", "San Francisco",
"Seattle"};
String target; // the city for which we are searching
int n; // loop counter
boolean found = false; // true if the target city is found in the
array
// set up input stream from the keyboard
Scanner keyboard = new Scanner(System.in);
// print intro message
System.out.print("This program will tell you if a city has an
NFL team.nn");
// get the target name of the city from the user
System.out.print("Please enter the name of a city: " );
target = keyboard.nextLine();
// search array of NFL cities for target city
// the loop coninues to the end of the array if the city is not
found
for (n=0 ; (!found) && (n < NFLcities.length) ; n++)
{
if (NFLcities[n].matches(target) ) // uses the String class
matches() method
{
//print found message and set found to true
System.out.println(target + " has an NFL team.n");
found = true;
} // end if
} // for loop
// after the loop – if not(found) print not found message
if (!found)
System.out.println(target + " is not in the list of cities with an
NFL team.n");
} // end main()
} // end class
JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 21
Sorting an Array
It is useful to be able to sort an array. There are many different
ways to do so, which are studied in
detail in CSCI 112 and CSCI 211. We will look at a simple
sorting method called a bubble sort.
In a bubble sort, we go through an array of data comparing each
data item to the next item. If they are
out of order, then we swap them; if they are in the correct order,
then we leave them alone. We
compare each item to the next item until we reach the end of the
array. Each time we go through the
entire array is called a pass through the array. We continue to
make passes until we can make one pass
all the way through the array without swapping anything. The
bubble sort is based on the transitive
property of equality and inequality (if A≤B and B≤C, then A≤B)
If we can make a pass without swapping
anything, then we know the array is in the correct order and
we’re done – the array is sorted.
We can use a boolean variable named swapped to keep track of
whether or not we needed to swap
anything in each pass through the array. Before we go through
the array, we set swapped to false. If we
swap anything, we also set swapped to true. When we finish a
pass, if swapped is true, then something
was swapped, and another pass is needed. If swapped is still
false after making a pass through the array,
then nothing needed to be swapped in that pass, and the array is
in the correct order; the sort is done.
Here is pseudocode for a bubble sort of an array. Notice that
each pass through the array only goes to
the second-to-last element in the array, since we are comparing
each element to the one that follows it.
The last comparison will then be between the second-to-last
element in the array and the last element.
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx
The Java Learning Kit Chapter 5 – Methods and Modular.docx

More Related Content

Similar to The Java Learning Kit Chapter 5 – Methods and Modular.docx

Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
Study Stuff
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
smumbahelp
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
smumbahelp
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes complete
Harish Gyanani
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
Prasanna Kumar SM
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
Raghavendra V Gayakwad
 
Core java questions
Core java questionsCore java questions
Core java questions
Pradheep Ayyanar
 
7494605
74946057494605
Oop in kotlin
Oop in kotlinOop in kotlin
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
Sujit Majety
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
Garuda Trainings
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
bhargavi804095
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
bhargavi804095
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
Vijay Kankane
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
nofakeNews
 
Core java-introduction
Core java-introductionCore java-introduction
Core java-introduction
Ramlal Pawar
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
AnmolVerma363503
 
OOPSCA1.pptx
OOPSCA1.pptxOOPSCA1.pptx
OOPSCA1.pptx
Soumyadipchanda2
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
BapanKar2
 

Similar to The Java Learning Kit Chapter 5 – Methods and Modular.docx (20)

Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
 
Mi0041 java and web design
Mi0041  java and web designMi0041  java and web design
Mi0041 java and web design
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes complete
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Core java questions
Core java questionsCore java questions
Core java questions
 
7494605
74946057494605
7494605
 
Oop in kotlin
Oop in kotlinOop in kotlin
Oop in kotlin
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
 
Lecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentationLecture5_Method_overloading_Final power point presentation
Lecture5_Method_overloading_Final power point presentation
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaion
 
Basics of java 1
Basics of java 1Basics of java 1
Basics of java 1
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Core java-introduction
Core java-introductionCore java-introduction
Core java-introduction
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
OOPSCA1.pptx
OOPSCA1.pptxOOPSCA1.pptx
OOPSCA1.pptx
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 

More from arnoldmeredith47041

Write a scholarly paper in which you apply the concepts of epide.docx
Write a scholarly paper in which you apply the concepts of epide.docxWrite a scholarly paper in which you apply the concepts of epide.docx
Write a scholarly paper in which you apply the concepts of epide.docx
arnoldmeredith47041
 
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docxWrite a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
arnoldmeredith47041
 
Write a Risk Management Plan for a School FacilityInclude th.docx
Write a Risk Management Plan for a School FacilityInclude th.docxWrite a Risk Management Plan for a School FacilityInclude th.docx
Write a Risk Management Plan for a School FacilityInclude th.docx
arnoldmeredith47041
 
Write a review that 750 - 1000 words in length about one chapter in .docx
Write a review that 750 - 1000 words in length about one chapter in .docxWrite a review that 750 - 1000 words in length about one chapter in .docx
Write a review that 750 - 1000 words in length about one chapter in .docx
arnoldmeredith47041
 
write a resume using the example belowCONTACT INFOFirs.docx
write a resume using the example belowCONTACT INFOFirs.docxwrite a resume using the example belowCONTACT INFOFirs.docx
write a resume using the example belowCONTACT INFOFirs.docx
arnoldmeredith47041
 
Write a resume and cover letter for the following positionOnline.docx
Write a resume and cover letter for the following positionOnline.docxWrite a resume and cover letter for the following positionOnline.docx
Write a resume and cover letter for the following positionOnline.docx
arnoldmeredith47041
 
Write a response to the peers post based on the readings. Origi.docx
Write a response to the peers post based on the readings. Origi.docxWrite a response to the peers post based on the readings. Origi.docx
Write a response to the peers post based on the readings. Origi.docx
arnoldmeredith47041
 
Write a response to the following prompt.Analyze the characteriz.docx
Write a response to the following prompt.Analyze the characteriz.docxWrite a response to the following prompt.Analyze the characteriz.docx
Write a response to the following prompt.Analyze the characteriz.docx
arnoldmeredith47041
 
Write a response to a peers post that adds or extends to the discus.docx
Write a response to a peers post that adds or extends to the discus.docxWrite a response to a peers post that adds or extends to the discus.docx
Write a response to a peers post that adds or extends to the discus.docx
arnoldmeredith47041
 
Write a response mini-essay of at least 150 to 300 words on  the dis.docx
Write a response mini-essay of at least 150 to 300 words on  the dis.docxWrite a response mini-essay of at least 150 to 300 words on  the dis.docx
Write a response mini-essay of at least 150 to 300 words on  the dis.docx
arnoldmeredith47041
 
Write a response for each document.Instructions Your post sho.docx
Write a response for each document.Instructions Your post sho.docxWrite a response for each document.Instructions Your post sho.docx
Write a response for each document.Instructions Your post sho.docx
arnoldmeredith47041
 
write a resonse paper mla styleHAIRHair deeply affects people,.docx
write a resonse paper mla styleHAIRHair deeply affects people,.docxwrite a resonse paper mla styleHAIRHair deeply affects people,.docx
write a resonse paper mla styleHAIRHair deeply affects people,.docx
arnoldmeredith47041
 
Write a response about the topic in the reading (see attached) and m.docx
Write a response about the topic in the reading (see attached) and m.docxWrite a response about the topic in the reading (see attached) and m.docx
Write a response about the topic in the reading (see attached) and m.docx
arnoldmeredith47041
 
Write a research report based on a hypothetical research study.  Con.docx
Write a research report based on a hypothetical research study.  Con.docxWrite a research report based on a hypothetical research study.  Con.docx
Write a research report based on a hypothetical research study.  Con.docx
arnoldmeredith47041
 
Write a Research Paper with the topic Pregnancy in the adolesce.docx
Write a Research Paper with the topic Pregnancy in the adolesce.docxWrite a Research Paper with the topic Pregnancy in the adolesce.docx
Write a Research Paper with the topic Pregnancy in the adolesce.docx
arnoldmeredith47041
 
Write a Research Paper with the topic Autism a major problem. T.docx
Write a Research Paper with the topic Autism a major problem. T.docxWrite a Research Paper with the topic Autism a major problem. T.docx
Write a Research Paper with the topic Autism a major problem. T.docx
arnoldmeredith47041
 
Write a research paper that explains how Information Technology (IT).docx
Write a research paper that explains how Information Technology (IT).docxWrite a research paper that explains how Information Technology (IT).docx
Write a research paper that explains how Information Technology (IT).docx
arnoldmeredith47041
 
Write a research paper outlining possible career paths in the field .docx
Write a research paper outlining possible career paths in the field .docxWrite a research paper outlining possible career paths in the field .docx
Write a research paper outlining possible career paths in the field .docx
arnoldmeredith47041
 
Write a Research paper on the Legal issues associated with pentestin.docx
Write a Research paper on the Legal issues associated with pentestin.docxWrite a Research paper on the Legal issues associated with pentestin.docx
Write a Research paper on the Legal issues associated with pentestin.docx
arnoldmeredith47041
 
Write a research paper on one of the following topics .docx
Write a research paper on one of the following topics .docxWrite a research paper on one of the following topics .docx
Write a research paper on one of the following topics .docx
arnoldmeredith47041
 

More from arnoldmeredith47041 (20)

Write a scholarly paper in which you apply the concepts of epide.docx
Write a scholarly paper in which you apply the concepts of epide.docxWrite a scholarly paper in which you apply the concepts of epide.docx
Write a scholarly paper in which you apply the concepts of epide.docx
 
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docxWrite a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
Write a S.M.A.R.T. goal to improve the Habit 5 Seek First to .docx
 
Write a Risk Management Plan for a School FacilityInclude th.docx
Write a Risk Management Plan for a School FacilityInclude th.docxWrite a Risk Management Plan for a School FacilityInclude th.docx
Write a Risk Management Plan for a School FacilityInclude th.docx
 
Write a review that 750 - 1000 words in length about one chapter in .docx
Write a review that 750 - 1000 words in length about one chapter in .docxWrite a review that 750 - 1000 words in length about one chapter in .docx
Write a review that 750 - 1000 words in length about one chapter in .docx
 
write a resume using the example belowCONTACT INFOFirs.docx
write a resume using the example belowCONTACT INFOFirs.docxwrite a resume using the example belowCONTACT INFOFirs.docx
write a resume using the example belowCONTACT INFOFirs.docx
 
Write a resume and cover letter for the following positionOnline.docx
Write a resume and cover letter for the following positionOnline.docxWrite a resume and cover letter for the following positionOnline.docx
Write a resume and cover letter for the following positionOnline.docx
 
Write a response to the peers post based on the readings. Origi.docx
Write a response to the peers post based on the readings. Origi.docxWrite a response to the peers post based on the readings. Origi.docx
Write a response to the peers post based on the readings. Origi.docx
 
Write a response to the following prompt.Analyze the characteriz.docx
Write a response to the following prompt.Analyze the characteriz.docxWrite a response to the following prompt.Analyze the characteriz.docx
Write a response to the following prompt.Analyze the characteriz.docx
 
Write a response to a peers post that adds or extends to the discus.docx
Write a response to a peers post that adds or extends to the discus.docxWrite a response to a peers post that adds or extends to the discus.docx
Write a response to a peers post that adds or extends to the discus.docx
 
Write a response mini-essay of at least 150 to 300 words on  the dis.docx
Write a response mini-essay of at least 150 to 300 words on  the dis.docxWrite a response mini-essay of at least 150 to 300 words on  the dis.docx
Write a response mini-essay of at least 150 to 300 words on  the dis.docx
 
Write a response for each document.Instructions Your post sho.docx
Write a response for each document.Instructions Your post sho.docxWrite a response for each document.Instructions Your post sho.docx
Write a response for each document.Instructions Your post sho.docx
 
write a resonse paper mla styleHAIRHair deeply affects people,.docx
write a resonse paper mla styleHAIRHair deeply affects people,.docxwrite a resonse paper mla styleHAIRHair deeply affects people,.docx
write a resonse paper mla styleHAIRHair deeply affects people,.docx
 
Write a response about the topic in the reading (see attached) and m.docx
Write a response about the topic in the reading (see attached) and m.docxWrite a response about the topic in the reading (see attached) and m.docx
Write a response about the topic in the reading (see attached) and m.docx
 
Write a research report based on a hypothetical research study.  Con.docx
Write a research report based on a hypothetical research study.  Con.docxWrite a research report based on a hypothetical research study.  Con.docx
Write a research report based on a hypothetical research study.  Con.docx
 
Write a Research Paper with the topic Pregnancy in the adolesce.docx
Write a Research Paper with the topic Pregnancy in the adolesce.docxWrite a Research Paper with the topic Pregnancy in the adolesce.docx
Write a Research Paper with the topic Pregnancy in the adolesce.docx
 
Write a Research Paper with the topic Autism a major problem. T.docx
Write a Research Paper with the topic Autism a major problem. T.docxWrite a Research Paper with the topic Autism a major problem. T.docx
Write a Research Paper with the topic Autism a major problem. T.docx
 
Write a research paper that explains how Information Technology (IT).docx
Write a research paper that explains how Information Technology (IT).docxWrite a research paper that explains how Information Technology (IT).docx
Write a research paper that explains how Information Technology (IT).docx
 
Write a research paper outlining possible career paths in the field .docx
Write a research paper outlining possible career paths in the field .docxWrite a research paper outlining possible career paths in the field .docx
Write a research paper outlining possible career paths in the field .docx
 
Write a Research paper on the Legal issues associated with pentestin.docx
Write a Research paper on the Legal issues associated with pentestin.docxWrite a Research paper on the Legal issues associated with pentestin.docx
Write a Research paper on the Legal issues associated with pentestin.docx
 
Write a research paper on one of the following topics .docx
Write a research paper on one of the following topics .docxWrite a research paper on one of the following topics .docx
Write a research paper on one of the following topics .docx
 

Recently uploaded

BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
zuzanka
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
National Information Standards Organization (NISO)
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
deepaannamalai16
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 

Recently uploaded (20)

BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptxRESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
RESULTS OF THE EVALUATION QUESTIONNAIRE.pptx
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.HYPERTENSION - SLIDE SHARE PRESENTATION.
HYPERTENSION - SLIDE SHARE PRESENTATION.
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 

The Java Learning Kit Chapter 5 – Methods and Modular.docx

  • 1. The Java Learning Kit: Chapter 5 – Methods and Modularity Copyright 2015 by C. Herbert, all rights reserved. Last edited January, 2015 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, Matthew Staley, and Daphne Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Spring 2015 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 5 Methods and Modularity
  • 2. Lesson 5.1 – User Created Methods in Java Lesson 5.2 – Method Parameters Lab 5A – Examining code with Several Methods Lesson 5.3 – Top-Down Design and Modular Development Lab 5B – Methods and Parameter Passing JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 2 Contents Chapter 5 Learning Outcomes ............................................................................................... ..................... 3 User Created Methods in Java ......................................................................................... 4 Method Modifiers ............................................................................................... ................................ 4 Return Type ............................................................................................... ......................................... 6 Other method modifiers ............................................................................................... ...................... 7
  • 3. Method Parameters ............................................................................................... ............................. 7 Invoking a Method and Parameter Passing ......................................................................................... 7 Method Documentation ............................................................................................... ...................... 9 CheckPoint 5.1 ............................................................................................... ................................... 10 Lab 5A – Examining code with Several Methods ................................................................................... 11 Top-Down Design and Modular Development .............................................................. 13 CheckPoint 5.2 ............................................................................................... ................................... 15 Lab 5B – Methods and Parameter Passing ............................................................................................ 16 Key Terms ............................................................................................... .............................................. 21 Chapter Questions ............................................................................................... ................................. 21
  • 4. Chapter Exercises ............................................................................................... ................................... 22 JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 3 The Java Learning Kit: Chapter 2 Reading, Writing, and Arithmetic This chapter introduces user-created methods in Java, along with the accompanying techniques of modular development and top-down design, also known as structured decomposition or functional decomposition. Parameter passing between methods and polymorphic method overloading are also discussed. Chapter 5 Learning Outcomes Upon completion of this chapter students should be able to:
  • 5. Oracle’s Java Tutorials. the difference between a formal parameter list and an actual parameter list. -down design of an algorithm, also known as structured decomposition or functional decomposition. and several advantages of developing software in smaller modules. demonstrating good modular design and the proper use of parameter passing between methods. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 4 User Created Methods in Java So far we have only created software with a single method, the
  • 6. main method in the single class in each Java application we created. We have invoked other methods from other classes, such as the Math class and the Scanner class, but we have only created one method at a time in our applications. Now we will begin to work with multiple methods of our own. The code for each method in Java software is defined in a method declaration within a class. A method declaration defines a method, with a method header, followed by a block of code marked by braces. According to Oracle’s Java tutorials, a method declaration has six components – the five parts of the method header and the method’s block of code1. A Java method header includes method modifiers (such as public and static), the return type of the method, the method name, a set of parentheses which contains the method’s parameters, and an exception list. The parentheses are blank if there are no parameters. In general the parts of a method header look like this: [modifiers] [return type] method name(formal parameter list) [exception list] Here is an example. This method has no exception list after the parameter list. If you do see the word
  • 7. throws after a parameter list, then that is the beginning of the exception list, which is also known as a thrown exception clause. We will learn about exceptions later in the course. public double overTime(double hours, double rate) { double overtimeHours; double overtimePay; overtimeHours = hours - 40; overtimePay = overtimeHours *rate * 1.5; return overtimePay; } // end (overtime(( double hours, double rate) Method Modifiers Method modifiers provide the compiler with information about the nature of the method. The most common method modifier is called the access modifier, which
  • 8. sets the access level for the method. Java methods may have public, private, or protected access. any other software. within the class which contains the method. 1 See: http://docs.oracle.com/javase/tutorial/java/javaOO/methods.htm l method header parameter list return type access modifier method name Figure 1 – parts of a method header JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 5 subclasses of a class may invoke protected
  • 9. methods. We learn about subclasses later in the semester when we learn about inheritance. Why Java Applications Need a Public Static Void Main() Method Every java application must start somewhere. A Java application can contain many methods in many different classes and can also import methods from classes that are not part of the application’s own source code, but that are defined elsewhere. At least one class in a Java application must have the same name as the application’s software package. This class must contain a method named main, which will be the method that is executed when the software application runs. The main method will contain any calls or references to other methods used within the application. A Java application’s main method must be public, which means it is available to be run from outside of its own software package. This is necessary so that the operating system can start the application by running the main method. This means that the access modifier public must be included in a main
  • 10. method’s header. An application’s main method is a class-level method, associated with the overall application’s and not with an instance of a class, therefore its header must have the access modifier static, which identifies class-level methods, variables, and so on. The main method for a java application does not return any values. Hence it must be marked with the access modifier void in the method’s header, which indicates it does not return any user defined values. Actually, when a java application terminates it will send a code to the operating system to indicate whether or not the application terminated normally. However, this message passing happens automatically, and we do not need to be concerned about it, at least not for now.) Putting all of this together, the modifiers public, static and void must come before the method name in the method header for a main method. For example, a payroll application whose application software package is named Payroll, must have a payroll class with the following method: public static void main( String[] args) {
  • 11. . . . method block of code follows . . . } // end main() The parameter for the main method is a String array of arguments, which is why main methods have the default parameter String[] args. (The terms parameter and argument mean almost the same thing, and are often used interchangeably.) Often this parameter goes unused, but it is there to enable operating system and the method to communicate with one another. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 6 Another common method modifier is the static modifier. According to the JLS, a method that is declared static is called a class method. A static method is associated with the class and not with an instance of the class. It is invoked by using the class name, and not the instance name, as part of its qualified name. The main methods in the software we have written so far have
  • 12. been declared public static void main(…). We have also seen static methods in the Math class. Methods such as Math.sqrt() and Math.random() are class level methods that have been invoked using the name of the class – the Math class. The Scanner class methods we have used were not class level methods. They were invoked using the name of an instance of the class. We had to declare a new instance of the Scanner class associated with a particular input stream before we could use methods such as nextLIne() in the example below. If the static modifier is missing, then the method is an instance method. If the static modifier is present, it is a class method. public static void main(String args[]) { String name; Scanner kb = new Scanner(System.in); // say hello to the user and ask for the user’s name System.out.println("Hello, please enter your name: "); name = kb.nextLine();
  • 13. . . . // the method continues . . . Return Type The return type in a method header declares the data type of the value the method returns, or uses the keyword void to indicate that the method does not return a value. A method that does not return a value is often called a void method. A void method is invoked from another method by using the void method’s name as if it is a new Java instruction. A method that returns a value can called from anyplace in another Java method where a variable or literal of the same data type can be used. For example, the Math.sqrt() method returns a value of data type double. Therefore, it can be called from any place that a variable type double or a double literal can be used, such as in a math expression. Methods that return a value, such as the Math.sqrt() method, are often called inline methods, because they can be invoked in a Java statement “inline”, as shown on the left. double result;
  • 14. double num1; result = 3 * num1 + 4; result = 3 * Math.sqrt(10) + 4; The nextLine() method that is invoked from the main() method in Figure 2, above, has a return type of String, so it can be used in a Java statement anyplace that a String value can be used. In this example, the value returned by the method is assigned to the String variable name. Figure 2 – part of a main() method The static modifier identifies the main() method as a class-level method. The nextLine() method is a instance method, invoked using the name of the instance of the Scanner class to which it applies, kb. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 7
  • 15. Other method modifiers There are several other modifiers, such as abstract, native, strictfp, and synchronized, that can be used in Java methods headers in addition to modifiers and return types discussed here. They are beyond what we need to use for now, but are listed and described online at: http://docs.oracle.com/javase/tutorial/reflect/member/methodMo difiers.html Method Parameters The list of variable declarations in parentheses following the name of the method is the formal parameter list. Formal parameters are local variables that will hold the values passed to the method when the method is invoked. They are declared in the method header by listing the data types and names of the variables. They may be used in the method just as any other local variables may be used. The scope of the variables declared in a formal parameter list is the body of the method in whose header the list appears. In the overtime example shown again in Figure 3, the double variables hours and rate are formal parameters, which are used as local variables within the method.
  • 16. Values will be passed to initialize these variables when the method is invoked from another method. The parameters that are passed to a method are also called the arguments of a method. /**************************************************** *************************/ /* The overtime method calculates the total overtime pay following the time * and a half for overtime rule. The result is to be added to the regular pay * for 40 hours. * * method parameters: * double hours -- hours worked this week – usually close to 40.0 * double rate -- employee's pay rate a decimal values usually less than 100 * * The method returns the total overtime pay for hours above 40 as a double. */ public double overTime( double hours, double rate) {
  • 17. double overtimeHours; // hours worked beyond 40 double overtimePay; // pay for overtime hours // calculate overtime hours and pay overtimeHours = hours - 40; overtimePay = overtimeHours *rate * 1.5; return overtimePay; } // end overtime (double hours, double rate) /**************************************************** *************************/ Invoking a Method and Parameter Passing There are two ways a method may be invoked from another method: a Java statement; user-created instruction in the Java language. The following examples show how to invoke methods. Figure 3 – a user-
  • 18. defined method http://docs.oracle.com/javase/tutorial/reflect/member/methodMo difiers.html JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 8 Example 1 - is a declaration for a method that returns a value. We can see from the method header that its return type is int. It also takes two integer parameters, a and b. // this method returns the lesser of two integer values public int lesser( int a, int b) { if ( b < a) return b; else return a; } // end lesser() The method may be used anyplace in a Java expression where an integer value can be used, such as in the following statement in another method:
  • 19. sum = grade 1 + grade2 + lesser(grade3, grade4); In Java, parameters can be passed by value. Parameter passing by value means that the values specified in the actual parameter list are passed to the variables declared in the formal parameter list. When a method is invoked, the data types of the actual parameters must match those of the formal parameters and the actual parameters must be in the same order as the formal parameters. In this case, the values of the variables grade3 and grade4 are the actual parameters for this invocation of the method. They are passed to the variables a and b in the method lesser(). The values of the variables grade3 and grade4 are used to initialize the variables a and b in the method lesser(). 91 93 grade3 grade4 91 93
  • 20. a b memory space for main() memory space for lesser() 94 87 grade1 grade2 If grade3 = 91 and grade4 = 93, then 91 is passed to a and 93 is passed to b. There is no connection between the variables in the two methods – the values from one are simply passed to the other. Example 2 - a value returning method named square // this method returns the square of a double value public double square( double x) { return x * x; } // end square() The square() method is invoked in each of the following statements: dist = Math.sqrt( square(dx) + square(dy) );
  • 21. area = square(s); area = square(2.5); actual parameters type Figure 4 – a method that returns an int value Figure 5 – parameter passing by value Figure 6 – a method that returns a double value JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 9 The square() method is called four times, twice in the first statement, once in the second statement., and once in the third statement. Notice that the third statement uses the value 2.5 as an actual
  • 22. parameter – no variable is used. This is perfectly acceptable when passing by value, as Java does. In the first statement, the value of dx is passed to square() and the return value is used in place of the method call square(dx), then the value of dy is passed to square() and the return value is used in place of the method call square(dy). In the second statement, the value of s is passed to the square() method and the formal parameter x is initialized to the value of s. Area will be equal to s2. In the third statement, the value 2.5 is passed to square and the formal parameter x is initialized to 2.5. Area will be equal to 2.52, which is 6.25. ***************************************************** ******************************** Example 3 - a void method public void printCheck(String name, double netPay) { System.out.println("Pay to the order of " + name); System.out.printf("%8.2f”, netPay ) } // end printCheck() A void method is used as if it is a new instruction in the Java language:
  • 23. printCheck(name, netPay); printCheck(“Mary Jones”, 371.28); printCheck( (fname + “ “ + lname), net); In each case, the program will invoke printCheck(), passing the values to the method. The method uses the data to print the checks, but no value is returned to the calling method. The parameter passing works the same with void methods as with value returning methods: the values in the actual parameter list are used to initialize the variables in the formal parameter list. In the first statement above, the values of the variables name and netPay in the calling method are used to initialize empName and netPay in the printCheck() method. Even though the two variables netPay have the same name, they are still different variables not connected to one another in any way. The value of one is simply used to initialize the other. In the second printCheck() statements above, literal values are specified. These values will be used to initialize name and netPay when printCheck() is invoked. Method Documentation
  • 24. The version of the overtime method shown in Figure 3 is reasonably well-documented. Documentation is an important part of programming. Method documentation is an important part of object-oriented programming. Information in a comment describing each method should include the method’s: nctions Figure 7 – a void method – used “inline” as if it is a new Java instruction JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 10 A method’s entry conditions include information about the variables in the formal parameter list – such as the range of values for each parameter – along with any other special conditions that must be set
  • 25. before the method runs. In the case of the overTime method in Figure 3, the expected values of the variables hours and rate are listed, but no special conditions are mentioned. The method documentation should briefly describe what the method does and how the method functions. It should tell the reader if any new or unusual techniques are used in the method. If there are several different way to do something, then the documentation should be clear about which way is used in this method. The documentation for the overTime() method in Figure 3 makes it clear that the “time and a half for overtime” rule was applied, and that the method returns the total pay for all overtime hours, not just the added half. A method’s exit conditions should describe what value, if any, a method returns and anything else the method does that has an effect outside of the method. Does it open a new I/O stream? Does it turn a hardware device on or off? If it does anything with an effect that will be present after the method runs, then the exit conditions should say so. In the case of the overtime method in Figure 3, the only exit
  • 26. condition is that it returns a value. The data type and meaning of the value returned should be clearly described. You should also do something with the documentation to clearly separate one method from another in a class. Programming styles differ, so there are many ways to do this. In the case of the overtime method, a line of stars and then a blank line are immediately placed at the end of the method. This makes it easier for a reader to distinguish between methods. Remember, the documentation will be stripped from the code when the software is compiled. It’s there to make it easier for people to read and understand the code, including you as the author of the code who may need to come back to a method months or years later and will need to understand how it works. All documentation should be clear and reasonably concise, but ease of understanding is the most important factor. It is worth the time to make sure that readers can understand your code. CheckPoint 5.1 1. What are the six parts of a method declaration in Java, according to Oracle’s Java Tutorials?
  • 27. 2. What do the method modifiers public, private, and static each mean in a method declaration? 3. What is a void method and how is it invoked form another method? 4. How is a value returning method invoked from another method? 5. What is a formal parameter list and how does it correspond to an actual parameter list? JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 11 Lab 5A – Examining code with Several Methods The following source code is in the NetBeans project PayMethods, included in the file payMethods.zip in the files for Week 5 in Canvas. It demonstrates the use of a value returning method and a void method. Your task is to download the file, unzip the NetBeans project, then open it in NetBeans and examine the code. You should be able to see how the a value returning method and a voids method are invoked from main, and how parameters are passed from the main method to calculateGross() and to payrollReport().
  • 28. Notice that calculateGross() and payrollReport() are both static methods. This is because main() is a static method, and static methods cannot call instance methods. You should run the program to see how it works, then perhaps try changing some of the actual parameters to specific values to see how that works. Notice the modularity of the program – we could change the print report formats, for example, without messing with the main() method. We could also modify the way overtime is calculated without changing any other methods. package paymethods; import java.util.Scanner; /* CSCI 111 Fall 2013 * Sample program - payroll methods * This program has an example of a value returning method and a void method */ public class PayMethods {
  • 29. public static void main(String[] args) { String fname; // employee's first name String lname; // employee's last name double hours; // hours worked in the week double rate; // hourly pay rate double gross; // gross pay (hours * rate) + overtime // set up input stream from the keyboard Scanner keyboard = new Scanner(System.in); // get employee's first name System.out.print("Please enter the employee's first name: " ); fname = keyboard.next(); // get employee's last name System.out.print("Please enter the employee's last name: " ); lname = keyboard.next(); // get employee's hours System.out.print("Please enter the hours for " + fname +" " +
  • 30. lname+ ": "); hours = keyboard.nextDouble(); // get employee's rate System.out.print("Please enter the pay rate for " + fname +" " + lname+ ": "); rate = keyboard.nextDouble(); Figure 8 – a payroll program composed of several methods JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 12 // call method to calculate gross // This value returning method is used inline, gross is set to the value it returns gross = calculateGross(hours, rate); // call method to print payroll report // this void method is used as if it is a new instruction in Java
  • 31. // the actual parameters must correspond with the method's formal parameter list payrollReport(fname, lname, hours, rate, gross ); } // end main() /**************************************************** *************************/ /* This method calculates gross pay using the time and a half for overtime rule. * it has two parameters, * the hours worked during the week double hrs * the pay rate double rt * * it returns the gross pay */ public static double calculateGross(double hrs, double rt ) { double gr; // gross pay double ot; // overtime pay
  • 32. gr = hrs * rt; if (hrs > 40) ot = (hrs-40) * .5 * rt; // overtime bonus else ot = 0; gr = gr + ot; return gr; } // end calculateGross /**************************************************** *************************/ /* this method prints a payroll report * it takes four parameters, * employeee's first name String fname * employee's last name String lname * the hours worked during the week double hrs * the pay rate double rate */
  • 33. public static void payrollReport(String fname, String lname, double hrs, double rt, double gross ) { // print the payroll report System.out.printf("%n%-12s%-12s%8s%8s%9s%n", "first", "last", "Hours", "Rate", "Gross"); System.out.printf("%-12s%-12s%8.2f%8.2f%,9.2f%n", fname, lname, hrs,rt, gross); } // end payrollReport() } // end class JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 13 Top-Down Design and Modular Development It’s hard to solve big problems. It’s easier to solve small problems than it is to solve big ones.
  • 34. Computer programmers use a divide and conquer approach to problem solving: This process is a combination of techniques known as top-down design and modular development. Top-down design is the process of designing a solution to a problem by systematically breaking a problem into smaller, more manageable parts. First, start with a clear statement of the problem or concept – a single big idea. Next, break it down into several parts. If any of those parts can be further broken down, then the process continues until you have a collection of parts that each do one thing. The final design might look something like this organizational chart, showing the overall structure of separate units that form a single complex entity. JLK Chapter 5 – Methods and Modularity DRAFT January 2015
  • 35. Edition pg. 14 An organizational chart is like an upside down tree, with nodes representing each process. The leaf nodes are those at the end of each branch of the tree. The leaf nodes represent modules that need to be developed and then recombined to create the overall solution to the original problem. Top-down design leads to modular development.Modular development is the process of developing software modules individually, then combining the modules to form a solution to an overall problem. Figure 9 – an organizational chart showing units that form a single complex entity Figure 10 the leaf nodes of an organizational chart JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 15 Modular development facilitates production of computer
  • 36. software because it: … makes a large project more manageable. Smaller and less complex tasks are easier to understand than larger ones and are less demanding of resources. … is faster for large projects. Different people can work on different modules, and then put their work together. This means that different modules can be developed at the same time, which speeds up the overall project. … leads to a higher quality product. Programmers with knowledge and skills in a specific area, such as graphics, accounting, or data communications, can be assigned to the parts of the project that require those skills. …makes it easier to find and correct errors. Often, the hardest part of correcting an error in computer software is finding out exactly what is causing the error. Modular development makes it easier to isolate the part of the software that is causing trouble. … increases the reusability of solutions.
  • 37. Solution s to smaller problems are more likely to be useful elsewhere than solutions to bigger problems. They are more likely to be reusable code. Reusable code is code that can be written once, then called upon again in similar situations. It makes programming easier because you only need to develop the solution to a problem once; then you can call up that code whenever you need it. Modules developed as part of one project, can be reused later as parts of other projects, modified if necessary to fit new situations. Over time, libraries of software modules for different tasks can be created. Libraries of objects can be created using object-oriented
  • 38. programming languages. Most computer systems are filled with layers of short programming modules that are constantly reused in different situations. Our challenge as programmers is to decide what the modules should be. Each module should carry out one clearly defined process. It should be easy to understand what the module does. Each module should form a single complete process that makes sense all by itself. Top-down development is used to figure out what the modules are needed in a software development project and how they should be organized. Modular development involves building those modules as separate methods, then combining them to form a complete software solution for the project. CheckPoint 5.2
  • 39. 1. What are Java’s nine built-in data types and how do they fit into four major categories? 2. Which Java built-in data type is not a primitive data type? 3. How do each of Java’s integer data types differ from one another? 4. What is a literal and how are literals represented for different built-in data types? 5. Describe the formats used to store floating point data in memory. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 16 Lab 5B – Methods and Parameter Passing In this example we will develop a modular solution for a
  • 40. problem that is similar to the homework assignment from chapter 3. We wish to input the x and y coordinates for two points in the Cartesian plane, and find the distance between the two, then print a report telling the user the distance between the two points and the quadrant that each point is in. The distance between two points whose coordinates are (x1,y1) and (x2, y2) is √��2 + ��2 where Δx is the difference between the two x coordinates (x1- x2)and Δy is the difference between the y coordinates (y1- y2). The example on the right also shows us that the quadrants of a Cartesian plane are numbered I through IV, with the following properties:
  • 41. -negative, the point is in Quadrant I. f x is negative and y is non-negative, the point is in Quadrant II the point is in Quadrant III. -negative and y is negative, the point is in Quadrant IV. Y axis X axis (4,4) Δy = 8 (0,0) Quadrant IQuadrant II Quadrant III Quadrant IV
  • 42. (-2,-4) Δx = 6 Once we understand the specifications, we can make an outline of what our software should do: 1. get the coordinates of two points: (x1, y1) and (x2, y2) 2. calculate the distance between the two points: -x2; deltaY = y1-y2; 3. determine which quadrant (x1, y1) is in: drant III 4. determine which quadrant (x2, y2) is in:
  • 43. 5. print results Figure 11 – two points in a Cartesian plane JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 17 The similarity of steps 3 and 4 indicate that this would be good place for reusable code – one method
  • 44. that can be used twice, but each time with different values passed to the method. Step 2 is also a good place for a method, with the details of the calculation in the method. Step 1 might seem like a good place for a method – we get four numbers from the user, each in the same manner. However, remember that methods can only return one value, so we really don’t gain much by making this a separate method. It is a judgment call and a matter of programming style – it could be done with four calls to one method, but in this case we will use four different sets of statements in the main method. Here in the design of our software, listing descriptions of the methods with return types and formal parameters:
  • 45. Void main() method Double CalcDistance(double x1, double y1, double x2, double y2) method ulate deltaX String findQuadrant( double x, double y)
  • 46. X >=0) && (Y<0) Q =“Quadrant IV” The code in Figure 12 starting on the next page was developed from these specifications. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 18 /* * program to calculate the distance between two points * CSCI 111 Fall 2103 * last edited Sept 24, 2013 by C. Herbert
  • 47. */ package twopoints; import java.util.Scanner; public class TwoPoints { // The main method gets x and y for two points // Calls methods to calculate the distance between the two // and to determine the quadrant of each point // then outputs the result public static void main(String[] args) { //declare variables double x1,y1,x2,y2; // coordinates of (x1,y1) and
  • 48. (x2,y2) double dist; // distance between (x1,y1) and (x2,y2) String Q1, Q2; // quadrant containing (x1,y1) and (x2,y2) // set up instacne of Scanner for input Scanner kb = new Scanner(System.in); // get input in prompt & capture pairs System.out.print("Enter the x coordinate of point 1 :"); x1 = kb.nextDouble(); System.out.print("Enter the y coordinate of point 1 :"); y1 = kb.nextDouble();
  • 49. System.out.print("Enter the x coordinate of point 2 :"); x2 = kb.nextDouble(); System.out.print("Enter the y coordinate of point 2 :"); y2 = kb.nextDouble(); // call calcDistance() dist = calcDistance( x1, y1, x2, y2); // call findQuadrant(point1) Q1 = findQuadrant(x1, y1); // call findQuadrant(point2) Q2 = findQuadrant(x2, y2);
  • 50. // output results System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")"); System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n"); System.out.printf("The distance between the two points is: %-8.2f%n", dist ); System.out.println("Point 1 is in " + Q1); System.out.println("Point 2 is in " + Q2); } // end main() /**************************************************** ************************/ Figure 12 – a program organized as 3 methods
  • 51. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 19 // this method calculates and returns the distance between two points public static double calcDistance(double x1,double y1,double x2,double y2) { double deltaX; // difference in x coordinates double deltaY; // difference in x coordinates double dist; // distance between (x1,y1) and (x2,y2) deltaX = (x1-x2); deltaY = (y1-y2);
  • 52. dist = Math.hypot(deltaX, deltaY); return dist; /* this whole method could be one line: * return Math.hypot( (x1-x2), (y1-y2) ); */ } // end calcDistance() { /**************************************************** ************************/ // this method returns the quadrant that contains the point public static String findQuadrant(double x,double y) { String Q; //quadrant message
  • 53. if ( (x >= 0.0) && (y >= 0.0) ) Q = "Quadrant I"; else if ( (x < 0.0 ) && ( y >= 0.0) ) Q = "Quadrant II"; else if ( (x < 0) && (y < 0.0) ) Q ="Quadrant III"; else // ( (x >= 0) && (y < 0.0) ) Q = "Quadrant IV"; return Q; } // end findQuadrant } // end class Here is sample output from the program:
  • 54. Enter the x coordinate of point 1 :3 Enter the y coordinate of point 1 :4 Enter the x coordinate of point 2 :-3 Enter the y coordinate of point 2 :-4 Point 1 is (3.0,4.0) Point 2 is (-3.0,-4.0) The distance between the two points is: 10.00 Point 1 is in Quadrant I Point 2 is in Quadrant III The code in Figure 13 on the next page contains an alternative version of the same program as Figure 12. To the user, the two programs look the same. They have
  • 55. identical input and output. They are in the Week 5 Canvas files. These two Java applications are the topic of the Week 5 class discussion. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 20 /* distance between two points - alternative programming style * CSCI 111 Spring 2015 last edited Sept 24, 2013 by C. Herbert */ package twopointsb; import java.util.Scanner; public class TwoPointsB {
  • 56. // The main method calls a methods to calculate the distance between // two points, then prints that distance and the quadrant of each point public static void main(String[] args) { double x1,y1,x2,y2; double dist; // input coordinates x1 = inCor("x", "1"); y1 = inCor("y", "1"); x2 = inCor("x", "2"); y2 = inCor("y", "2");
  • 57. dist = Math.hypot( (x1-x2), (y1-y2) ); System.out.println("nPoint 1 is ("+ x1 + "," + y1 + ")"); System.out.println("Point 2 is ("+ x2 + "," + y2 + ")n"); System.out.printf("The distance between the two points is: %-8.2f%n", dist ); printQuadrant("1", x1 , y1); printQuadrant("2", x2 , y2); } // end main() /**************************************************** ************************/ // this method gets as input a single coordinate of a point public static double inCor(String axis, String point) {
  • 58. // set up instance of Scanner for input Scanner kb = new Scanner(System.in); // get coordinate with prompt System.out.print("Enter the " + axis + " coordinate of point " + point + " :"); return kb.nextDouble(); } // end inCor() /**************************************************** ************************/ // this method prints the quadrant a point is in public static void printQuadrant(String P, double x,double y) {
  • 59. if ( (x >= 0.0) && (y >= 0.00) ) System.out.println( "Point "+ P + " is in Quadrant I"); else if ( (x < 0.0 ) && ( y >= 0) ) System.out.println( "Point "+ P + " is in Quadrant II"); else if ( (x < 0) && (y < 0) ) System.out.println( "Point "+ P + " is in Quadrant III"); else // ( (x >= 0) && (y < 0) ) System.out.println( "Point "+ P + " is in Quadrant IV"); } // end printQuadrant } // end class Figure 13 –Figure 12’s program reorganized.
  • 60. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 21 Key Terms access modifier, 4 entry conditions, 10 exit conditions, 10 formal parameters, 7 inline methods, 6 leaf nodes, 15 method declaration, 4 method header, 4
  • 61. method modifiers, 4 modular development, 16 organizational chart, 14 parameter passing by value, 8 private access, 4 protected access, 4 public access, 4 return type, 6 reusable code, 16 static method, 6 throws, 4 top-down design, 14 void, 6
  • 62. Chapter Questions 1. So far this semester we have only created one method at a time in our applications, but what are some examples of methods from other classes that we have invoked in our source code? 2. What is included in a method declaration? 3. What are the parts of a method header? 4. What is in the parentheses that follow the name of the method in a method header? What does it mean if the parentheses are blank? 5. What does it mean if the word throws follows a method header? 6. Where does the return type belong in a method header? 7. What are the three access modifiers used in Java? What does
  • 63. the private access modifier do? 8. When do we need a main method in a class? What modifiers should be used with this method? 9. What does the JLS tell us about a method with the modifier static? How is a static method invoked? 10. What methods that we have previously used were static methods? What methods that we have previously used were associated with an instance of a class? 11. What do we call a method that does not return as value? What return type does it have? 12. Where can we use a method that returns a double value? 13. What is a method that can be invoked in a Java expression often called? 14. What is the difference between the formal parameter list and the actual parameters? Which of the two declares new variables for a method? Which contains values
  • 64. used to initialize variables? JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 22 15. What should be included in a comment describing each method? What happens to this documentation when a method is compiled? 16. What should be described as part of a method’s entry conditions? What should be described as part of a method’s exit conditions? 17. In what two ways can a method be invoked from another method? How is a value returning method invoked? How is a void method invoked? 18. How are parameters passed in Java? How must the values of the actual parameters be organized when a
  • 65. method is invoked? 19. When breaking a method down into parts using top-down design, which nodes on an organizational chart need to be developed and then recombined to create the overall solution to the original problem? 20. What are five of the ways in which modular development facilitates production of computer software? Chapter Exercises 1. Match the actual parameters on the left with the correct formal parameter list on the right. (3,4) (2.0,3.0) (“Jones”, 97.5) (“J00123453”, “B”) (42, 10.50) (double hours, double rate) (String name, double pay)
  • 66. (short people, double PoundsOfCake) (String Jnumber, String grade) (int length, int width) 2. Multiplication Table A set of nested for loops can be used to print a multiplication table using System.out.printf statements. 1 2 3 4 5 6 7 8 9 1 1 2 3 4 5 6 7 8 9 2 2 4 6 8 10 12 14 16 18 3 3 6 9 12 15 18 21 24 27 4 4 8 12 16 20 24 28 32 36 5 5 10 15 20 25 30 35 40 45 6 6 12 18 24 30 36 42 48 54 7 7 14 21 28 35 42 49 56 63
  • 67. 8 8 16 24 32 40 48 56 64 72 9 9 18 27 36 45 54 63 72 81 Write a program to print such a multiplication table, using a method to print each row, which is invoked from the method that prints the overall multiplication table. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 23 3. Printing Patterns Nested for loops can print patterns of stars, such as the example below: for(i=1; i<=5; i++)
  • 68. { for(j=1; j<=10; j++) { System.out.print(“*”); } // end for j System.out.println(); } // end for i Output from this program: ********** ********** ********** ********** ********** Write a program with a main method which asks the user for the number of rows and for the number of columns, then calls a method which uses that information to print a rectangle of stars.
  • 69. 4. Celsius to Fahrenheit Table Write a program to print a Celsius to Fahrenheit conversion table that invokes a method to calculate Fahrenheit temperature using formula is F = ( 9.0 5.0 C) + 32.0. The main method should have a loop to print the table, calling the conversion method from within the loop. The table should include integer Celsius degrees from 0 to 40. You program does not need to use integers, but the table should display the Celsius temperature, then the Fahrenheit accurate to one- tenth of a degree. The first few entries from the table are shown below: Celsius Fahrenheit 0 32.0 1 33.8
  • 70. 2 35.6 3 37.4 5. We wish to write a modular program that can be used to calculate monthly payments on a car loan. The formula is: payment = ������ ����∗ ������ 1−(1+������ ����)−����ℎ� The program will be composed of several methods – a main method, a monthly interest rate method, a monthly payment method, and an output method. The main method should: 1. ask the user for - the loan amount
  • 71. - the annual interest rate ( as a decimal, 7.5% is 0.075 ) - the number of months 2. call a method to calculate and return the monthly payment (Note: The formula uses monthly rate. Annual rate is input. monthly rate = annual rate/12) 3. call a method to print a loan statement showing the amount borrowed, the annual interest rate, the number of months, and the monthly payment JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 24 6. International Gymnastics Scoring
  • 72. We wish to write a program to quickly calculate gymnastics scores for an international competition. Six judges are judging the competition, numbered 1 through 6 for anonymity. The program should have a loop that: 1. calls a method asking for the score from a single judge, The method should print the judge number and score and return the judges score 2. adds the returned score to a total score. After the loop is done, your program should call a method that calculates and displays the average score. Scores are in the range 0 to 10 with one decimal place, such as 8.5. The average should be displayed with two decimal places.
  • 73. Here is a sample of the output: Score for Judge 1: 8.5 Score for Judge 2: 8.7 Score for Judge 3: 8.4 Score for Judge 4: 9.1 Score for Judge 5: 8.9 Score for Judge 6: 9.0 The average score is: 8.77 7. Test for Divisibility If the remainder from dividing A by B is zero, then A is a multiple of B ( A is evenly divisible by B ). For example, the remainder from dividing 6, 9, or 12 by 3 is 0, which means 6, 9, and 12 are all multiples
  • 74. of 3. Write a program with a loop to to print the numbers from 1 to 25, and within the loop, invokes a method to see if the number is a multiple of 2, a method to see if the number is a multiple of 3, and a method to see if the number is a multiple of 5. The methods should each print a message if the number is a multiple of the value for which they are testing. Here is a sample of part of the output: 1 2 multiple of 2 3 multiple of 3 4 multiple of 2 5 multiple of 5
  • 75. 6 multiple of 2 multiple of 3 7 8 multiple of 2 9 multiple of 3 10 multiple of 2 multiple of 5 JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 25 8. Estimate of a Definite Integral Write the program to estimate a definite integral with rectangles, with a loop that calls a method to calculate the height and area of each rectangle.
  • 76. A loop in a computer program can be used to approximate the value of a definite integral. We can break the integral into rectangles, find the area of each rectangle then add the areas together to get the total area, as shown in the accompanying diagram. In practice, we could make the width small enough to achieved the desired accuracy in estimating the area under the curve. y = 9-x2 area under the curve estimated by rectangles As the width of the rectangles gets progressively smaller, their total area gets closer to the total area under the curve. This is an old method that predates Calculus. Both Leibnitz and Newton used this
  • 77. method, eventually developing calculus from the concept of infinitesimals, which, in the case of our rectangles, would amount to asking, what would the total area be if we had very many rectangles with very small width? This was tedious by hand, but we now have computers. We can set the width of the rectangle. The height of the rectangle is the y value at point x. So for example, if we need to solve: ∫ 9 − �2 �� −3 +3 The starting point is -3, the ending point is +3, and the height of the rectangle at each value of x in between the two is 9 − �2 ; Y at each x is the is the height of the rectangle at that x. We can use a width
  • 78. of 0.001, and write a loop like this: for x = -3 to +3 step 0.0001 // x is -3.00, then -2.9, then -2.8, etc. { y = 9 − �2 ; // the height is the y value at each x area = y * .01; // the width is the increment, in this case 0.1 totalArea = totalArea + area; } In this version of the program, the statements in the box above should be in a separate method, invoked from within the loop. When the loop is finished, totalArea is the total area of the rectangles, which is an approximation of the area under the curve.
  • 79. Your lab report should explain what you did, and the result of your work. JLK Chapter 5 – Methods and Modularity DRAFT January 2015 Edition pg. 26 9. Supermarket Checkout Design a program for a terminal in a checkout line at a supermarket. What are the tasks that are included as part of checking out at a register? We must consider things like the cost of each item, weighing produce and looking up produce codes, the total cost of the order, bonus card discounts, and sales tax on taxable items only. You do not need to write the program, but you should design the methods using top down development and modular design. Submit a description of the methods
  • 80. needed for the program, a brief description of what each method does, and a description of how the methods are related to one another in terms of parameter passing and return types. 10. We wish to write a program to draw the scene below. We can create methods to draw primitive shapes, as follows: circle() takes x and y coordinates of center point, the radius, and the color triangle() takes x and y coordinates of each of three endpoints and the color rectangle() takes x and y coordinates of each of four corner points and the color Create a modular design for software to draw the scene using the methods above. The software should be layered. For example, a house() method should use the
  • 81. primitive graphics methods to draw the house. Your design document should list and briefly describe each method, including and what it does, parameters, and any methods the method calls. Your list should start with the main method. — End of Chapter 5 — The Java Learning Kit: Chapter 6 – Arrays
  • 82. Copyright 2015 by C. Herbert, all rights reserved. Last edited January, 2015 by C. Herbert This document is a chapter from a draft of the Java Learning Kit, written by Charles Herbert, with editorial input from Craig Nelson, Christopher Quinones, Matthew Staley, and Daphne Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Spring 2015 semester. This material is protected by United States and international copyright law and may not be reproduced, distributed, transmitted, displayed, published or broadcast without the prior written permission of the copyright holder. You may not alter or remove any trademark, copyright or other notice from copies of the material. The Java Learning Kit: Chapter 6
  • 83. Arrays Lesson 6.1 – Arrays Lesson 6.2 – One Dimensional Arrays in Java Lesson 6.3 – Operations on Numeric Arrays Lesson 6.4 – Searching and Sorting Arrays Lesson 6.5 – Text File Input and Output in Java Lab 6 – Programming Example: Moving Data between Arrays and Files JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 2 Contents Chapter 6 Learning Outcomes ............................................................................................... ..................... 3 Arrays
  • 84. ............................................................................................... ............................... 4 Array Storage in Computer Memory ............................................................................................... .... 5 CheckPoint 6.1 ............................................................................................... ..................................... 6 One Dimensional Arrays in Java ...................................................................................... 7 What is actually in an array in Java? ............................................................................................... .... 7 Assigning Values to Array Elements ............................................................................................... ... 10 The Array length Property; Iterating an Array ................................................................................... 11
  • 85. The Enhanced for Statement ............................................................................................... ............. 12 Copying an Array ............................................................................................... ................................ 13 Arrays as Method Parameters in Java ............................................................................................... 13 Passing an Array Element as a Method Parameter ........................................................................... 15 CheckPoint 6.2 ............................................................................................... ................................... 15 Operations on Numeric Arrays ...................................................................................... 16 Sum, Average, and Count of Values in an Array ................................................................................ 16
  • 86. The Minimum and Maximum Values in an Array .............................................................................. 17 Searching and Sorting Arrays ........................................................................................ 18 Comparing Strings ............................................................................................... .............................. 18 Linear Search of an Array ............................................................................................... ................... 18 Sorting an Array ............................................................................................ ... ................................. 21 Swapping the Values of Two Variables ............................................................................................. 22 CheckPoint 6.4 ............................................................................................... ................................... 24
  • 87. Text File Input and Output in Java ................................................................................. 25 Handling Data File Exceptions like Hot Potatoes ............................................................................... 26 A Technique for Writing Text Data Files using Java ........................................................................... 27 A Technique for Reading Text Data Files using Java .......................................................................... 28 CheckPoint 6.5 ............................................................................................... ................................... 29 Lab 6 – Programming Example: Moving Data between Arrays and Files ............................................. 30 Key Terms ............................................................................................... .............................................. 35 Chapter Questions
  • 88. ............................................................................................... ................................. 36 Chapter Exercises ............................................................................................ ... ................................... 37 JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 3 The Java Learning Kit: Chapter 6 Arrays This chapter introduces the concept of an array and working with arrays in Java, along with the use of text files in Java applications for long-term storage of arrays and other data. Lesson 1 introduces the concept of an array as a set of subscripted variables, including a look at
  • 89. how arrays are stored in memory. Lesson 2 shows how to implement arrays for Java’s built-in data types. Lesson 3 discusses simple statistical processing of numeric arrays — finding the sum, average minimum, and maximum in an array of numbers. Lesson 4 looks at simple techniques for searching and sorting arrays. Lesson 5 introduces simple text file I/O in Java. Chapter 6 Learning Outcomes Upon completion of this chapter students should be able to: stored in a computer’s memory. an array in Java; and how to declare an
  • 90. array, initialize an array, and iterate an array in Java. parameter in Java; and how to pass an individual array element as a method parameter in Java. iterate an array; and pass both references to arrays and individual array elements as parameters. operations on numeric arrays, including counting array elements, and finding the sum, average, minimum and maximum of values in an array.
  • 91. sum, average, minimum and maximum of values in an array. algorithm for a linear to search of an array. two variables, search an array, and sort an array. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 4 Arrays Until now we have been using single variables in our Java programs. Java, like most other programming
  • 92. languages, Java also supports arrays. An array is a set of indexed variables, all of the same data type. Instead of just having individual variables such as x, y, or empName, we can have a set of indexed variables such as x1, x2, x3, … and so on, where the value of the index identifies an element of an array. Each element of an array is an individual data item in the array, such as: empName0, empName1, empName2, … empNamen-1 In mathematics, such an array is also referred to as a set of subscripted variables, because the index is written as a subscript. In Java, they may also be called subscripted variables, but instead of using subscripts, Java uses square brackets following the variable name to indicate an array or an element in an array. empName0, empName1, employname2… from
  • 93. mathematics would be written as empName[0] , empName[1], empName [2] … empName [n-1] in Java. empName is the name of the array; whereas empName[i], where i is an integer, is an element in the array empName. The index values in an array start at zero for reasons we will see later in this chapter. empName[0] , empName[1], empName[2] … empName[n-1] Arrays are very useful for storing and working with sets of similar data items, such as lists of test scores. We will see how to set up an array to hold a set of numbers, such as test scores, then write code to find the sum, the average, the minimum or the maximum of the numbers. Once data has been established in the computer’s memory as an array, we can do many things with the data, including conducting a full statistical analysis of the data, searching the data for specific
  • 94. items, or sorting the data. Later, when we learn to work with objects, we can set up an array of objects, such an array of student records with properties like student number, first name, last name, address, and major, then we can sort or search through the data according to any of the object’s properties. But for now, we will only work with arrays of primitive data types and Strings. Most high-level programming languages support using arrays of data. They generally have two different type of arrays, single-dimensional arrays and mutli-dimensional arrays. A single dimensional array, also called a linear array, is an array with only one index variable, forming what can be thought of as a line of data items. The above example of empName[0] , empName[1], empName [2] … empName [n-1] is a one
  • 95. dimensional linear array. Multi-dimensional arrays have multiple index variables, such as the two-dimensional array shown here: a0,0 a0,1 a0,2 . . . a0,n a1,0 a1,1 a1,2 . . . a1,n a2,0 a2,1 a2,2 . . . a2,n am,0 am,1 am,2 . . . am,n This is a two dimensional array from the world of mathematics, forming a table with m rows and n columns. In Java, the array would look like this: JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 5 a[0,0] a[0,1] a[0,2 ]. . . a[0,n] a[1,0] a[1,1] a[1,2 ]. . . a[1,n]
  • 96. a[2,0] a[2,1] a[2,2 ]. . . a[2,n] a[m,0] a[m,1] a[m,2] . . . a[m,n] Two dimensional arrays can be used to represent tables of data with rows and columns of information, similar to an electronic spreadsheet. They are often used for matrices in linear algebra problems. Multi-dimensional arrays can have more than two dimensions. A three dimensional array could, for example, represent a three-dimensional matrix for solving problems related to three-dimensional Euclidean space with x, y, and z coordinates. However, for the remainder of this chapter we will stick with simple single dimensional arrays, leaving the more complex problems for another day. Array Storage in Computer Memory
  • 97. The values for variables in a computer program are stored in a computer’s internal memory while the program runs. Hence, each variable name is associated with a specific address in the computer’s memory. This matching of variables to memory addresses is usually managed by the computer’s operating system with a symbol table. A symbol table is a list of symbolic names, such as the names of methods, classes, and variables, mapped to specific addresses in a computer’s internal memory. Almost all modern computer systems have byte addressable memory, meaning that bytes in a computer’s memory are sequentially numbered, regardless of the word length of a particular processing unit. There are many advantages to this, which are discussed in computer architecture and organization courses such as CSCI 213– Computer Organization at
  • 98. Community College of Philadelphia. The following example shows how an operating system keeps track of the values of variables using a symbol table. The memory map shows us how space is allocated in the computer’s memory. variables symbol table memory map int score; score 4000 4000 score double velocity; velocity 4004 4001 int colorDepth; colorDepth 400C 4002 boolean transparent; transparent 4010 4003 4004 velocity 4005 Memory is allocated according to how variables are declared. 4006
  • 99. Space is allocated based on data types, as described back in chapter 2, for example: int 32 bits (4 bytes) double 64 bits (8 bytes) boolean (1 byte in this system) The symbol table records where variables are stored in the internal memory. Memory addresses are hexadecimal (base 16). 4007 4008 4009 400A 400B 400C color depth 400D 400E
  • 100. 400F 4010 transparent JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 6 When an array is declared, the operating system only keeps track of array’s base address, which is the location where the array starts in memory. Here is an example: CheckPoint 6.1 1. What is the relationship among the terms array, indexed variables, and subscripted variables? 2. What is a linear array? 3. What does it mean to say that most computers use byte- addressable memory?
  • 101. 4. If array begins at memory address 5000 and each array element requires 16 bits of storage space, where will the array element with index 3 be stored in memory? 5. How can arrays be used to represent tables of data with rows and columns, similar to an electronic spreadsheet? variables symbol table memory map priority = new int [6]; priority 4000 4000 priority [0] int score; score 4018 4001 4002 The symbol table only contains the base address of an array. Since all of the elements of the array are the same data type, they will all use the same number of bytes in memory. So, the computer calculates the address of an element in an array using the formula:
  • 102. memory address = base address + (index * size) In this example, the base address for the array priority is 4000. The size of each element is 4 bytes, since it is an array of integers. So, the address of priority[2] is: address of priority[2] = 4000 + 2 * 4 which equals 4008. (Remember, addresses are base 16 – hexadecimal). This scheme works because the index of the first element in the array is 0, not 1. In fact, this is why array index values start at 0. Notice that the highest index is one less than the size of the array, because the array index numbering starts at zero. In this example priority has 6 elements, priority[0] through priority[5]. 4003 4004 priority [1]
  • 103. 4005 4006 4007 4008 priority [2] 4009 400A 400B 400C priority [3] 400D 400E 400F 4010 priority [4]
  • 104. 4011 4012 4013 4014 priority [5] 4015 4016 4017 4018 score 4019 401A 401B JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 7
  • 105. One Dimensional Arrays in Java A one-dimensional array in Java is a indexed fixed-length homogeneous data structure. In other words, it is a set of sequentially numbered data elements, in which all of the data must be of the same data type, and with a number of elements that cannot be changed. In Java, an array is an object. There are two parts to declaring an array in Java, unlike primitive data types, which have a one-step declaration. First, the array must be named; second, the size must be declared. step 1 – Declare a name for the array. There are two styles for doing this, which both assign a name to an array, but do not create the array in memory: (The first style is preferred.) int[] score; // declares score to be the name of an int array, it
  • 106. has no elements int score[]; // declares score to be the name of an int array, it has no elements step 2 – Declare the size of the array. score = new int[10]; // declares the array score to have 10 integer elements The number in brackets is the number of elements or size of the array, also known as the array length. The indexes in Java arrays must be non-negative and always start at zero. The highest index will be one less than the size of the array. If the array length is n, then the highest index will be n-1. The statement that declares the array length actually creates the array. The two statements naming an array and declaring an array must both be used to create the array:
  • 107. int[] score; score = new int[10]; The name and size declarations for an array can be put together in one Java statement, which is the easiest and most common way to create an array in Java: int[] score = new int[10]; // score is the name of an integer array with 10 elements The keyword new is necessary when declaring objects. An array is an object in Java. This statement declares an array named score and sets the size to 10 elements. What is actually in an array in Java? Each element in an array is an individual variable of the data type declared for the array. For example, if empName is declared as: String[] empName = new String[10];
  • 108. then each of the array elements, such as empName[3], is a String variable. If the data type of an array is a primitive data type, then each element of the array contains a value of that data type. If the data type of an array is a class of objects, then each element in the array contains a memory address referring to where an object of the correct data type is stored in memory. A memory address referring to where an object is stored is called a reference to an object. Java Strings are objects, so each element in a String array holds a reference to a String, not the String itself. Example 1 – an integer array JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 8
  • 109. An array of integers contains the actual values of integers, since int is a primitive data type. int[] score = new int[5]; This statement creates an array of integers named score with 5 elements. The actual values of integers would be stored in the each element in the array, such as: memory address variable name for this address value stored at this address 4000 score[0] 93 4004 score[1] 87 4008 score[2] 91
  • 110. 400C score[3] 95 4010 score[4] 88 We can think of an array as a set of empty boxes. In the integer array score, each box holds an integer: Score[] 93 87 91 95 88 Example 2 – A String array With any array of objects, including a String array, the elements of the array actually contain references to the objects, not the objects themselves. So, an array of Strings would contain references to where the Strings themselves are stored in memory, like this: String[] empName = new String[5]; memory
  • 111. address variable name for this address value stored at this address 4000 empName[0] ….4184 4004 empName[1] ….4210 4008 empName[2] ….4258 400C empName[3] ….510C 4010 empName[4] ….4412 This example assumes that each memory address is 32 bits (4 bytes) long, but only the last 4 hexadecimal digits are shown. The Strings are actually stored in the memory locations referenced by the values in the array.
  • 112. If we think of an array as a set of empty boxes, then each box in the String array empName, holds a reference to where a String value is actually stored in memory: empName[] ….4184 ….4210 ….4258 ….510C ….4412 “Jones” “Goldschneider” “Brown” (and so on…) Why does Java store arrays of objects this way? Remember, an array is a fixed length data structure, but Strings and many other objects are not fixed length, their sizes can change. This method for storing objects in memory allows variable length objects to be store in fixed length arrays. It also has several advantages that are beyond the scope of what we cover in this chapter.
  • 113. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 9 Even though the elements of a String array actually contain references to Strings, if we use a variable from the array in our Java code, we will get the String, not the reference. For the example above: System.out.println( empName[2] ); //prints the name Brown, not the reference ….4258 Once we learn to work with objects, we will see that we can have an array for any type of object, just as with Strings, using references to the objects stored in memory, such as an array of images: Example 3 – an Array of Images JPGimage[] orientation = new JPGimage[5]; orientation[]
  • 114. 4100 6404 7820 880C B204 … and so on. Each element in the array contains a reference to a stored image. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 10 Assigning Values to Array Elements There are two ways to assign values to array elements: 1. using assignment statements For example: score[3] = 98; // an int value is assigned to the fourth element in score
  • 115. empName[0] = “Jones”; // a String value is assigned to the first element in empName a[4] = x; // a[4] is set to the value of x (data types must match) 2. by listing values in an alternate array declaration Arrays may be declared in a statement that lists their values: int[] score = {93, 87, 91, 95, 88}; This method is sometimes called an explicit array declaration. The values listed in braces, separated by commas, are assigned in order to the array elements. The length of the array is determined by the number of values in the list. The keyword new is not needed in an explicit array declaration. An explicit array declaration like the one just shown above works well for small arrays, but can be
  • 116. awkward for large arrays. One common way to initialize the values in an array is with a count controlled loop. Here are a few examples: Example 4 – Initializing all of the elements in an Array to Zero The following code initializes the values of an array of data type double all to the same value, zero: double[] cost = new double[100]; // an array of 100 numbers for(int i=0; i<100; i++) cost[i] = 0.0; Example 5 – Initializing an Array with User Input The following code initializes the values of an array of data type String with user input. Inside the array
  • 117. the names are numbered starting with 0, but to the user they are numbered starting with 1. This assumes that the code is encapsulated, meaning that the user does not see the code. String[] student = new String[10]; // an array of 10 student names for( int i= 0; i < 10; i++) { // Ask the user for a student name, then get the name from the keyboard System.out.print("Please enter the name of student number" + (i+1) + “:” ); student[i] = x.nextLine(); } // end for
  • 118. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 11 Example 6 – Initializing an Array with random numbers The following code initializes the values of an int array with random numbers between 1 and 100. An array of random numbers is often used in game or simulation programming, or to test other software. int [] num = new int[100]; // an array of 100 integers for( int i= 0; i < 100; i++) num[i] = 1+(int)(Math.random()*100); // random, 1 <= num[i] <= 100 Math.random() yields a value between 0 and 1; the arithmetic converts it to a integer between 1 and 100. The Array length Property; Iterating an Array x.length, where x is the name of an array, is a method for
  • 119. instances of array objects that returns the length of the array as an integer. For example, if the array score[] has 10 elements, then score.length returns the value 10. The length property can be used to iterate an array. To iterate an array means to go through each of the elements in the array on at a time. The three examples above each iterate an array, and could be written to use the length property. Here is the code from example 4, above, re-written using the length property for the cost array. Example 7 – Initializing an Array using the length method double[] cost = new double[100]; // an array of 100 numbers for(int i = 0; i < cost.length; i++) cost[i] = 0.0;
  • 120. There are many different reasons to iterate an array – to initialize the array as above, or to print the elements of the array, for example. Example 8 – Printing the Elements of an Array // the following assumes student is a String array that has been initialized for( int i= 0; i < student.length; i++) System.out.print("Student number " + ( i+1) + “ is ” + student[i]); Example 9 – Printing the Fibonacci numbers The Fibonacci sequence is a sequence of numbers that starts with 0 and 1, then each successive term in the sequence determined by adding the previous two terms. Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
  • 121. Such a pattern is very common in the natural world. The following diagrams help us to understand why that is so. On the left, we see a set of rectangles composed by adding squares whose sides are successively larger Fibonacci numbers. The next square to be added will have a side of length 13, and will be added above the existing rectangle. On the right we see a spiral drawn by connecting the corners of Fibonacci squares. The growth of branches on a tree, the shape of a spiral sea shell, the pattern of seeds on a sunflower, the growth of a population of rabbits, and many other patterns in the real world fit the Fibonacci sequence. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 12
  • 122. In this example, we will store the first 10 Fibonacci numbers in an array named fib[], then print the array. We will declare the array using a set of values. int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with Fibonacci numbers int i;// used as an array index System.out.println(“The first ten Fibonacci numbers” ); // this loop prints the values in the array for( i= 0; i < fib.length; i++) System.out.print(fib[i] + “ “); System.out.println(); // go to a newline after printing the array values The output looks like this:
  • 123. The first ten Fibonacci numbers 0 1 1 2 3 4 5 8 13 21 34 The Enhanced for Statement The for statement we have been using so far is the basic for statement. Java also has a special version of the for statement, called the enhanced for statement. The enhanced for statement iterates an entire array. It may only be used with an array or an object that can be iterated like an array. The enhanced for statement has a loop header with the keyword for, followed by parentheses that contain an integer declaration and the name of an array. The statement or block of code following the loop header will be executed once for each element in the array. Within the statement or block of code, the integer declared in the loop header refers to each element in
  • 124. the array. The syntax within an enhanced for loop can be tricky, so be careful. We do not use the name of the array within the loop, only the integer variable declared in the header. This variable refers to an element of the array, sequentially incremented each time through the loop. Here is the syntax of the enhanced for loop: for ( integer declaration : name of an array) block of code Here is the same code from above to print the array with the first 10 Fibonacci numbers, using an enhanced for loop instead of a basic for loop:
  • 125. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 13 Example 10 – the enhanced for loop int[] fib = {0,1,1,2,3,5,8,13,21,34} // an array initialized with Fibonacci numbers System.out.println(“The first ten Fibonacci numbers” ); // this loop prints the values in the array using the enhanced for statement for(int i : fib) System.out.print(i + “ “); // i refers to fib[i] in this enhanced for loop System.out.println(); // go to a newline after printing the array values The output looks like this: The first ten Fibonacci numbers
  • 126. 0 1 1 2 3 4 5 8 13 21 34 Although it is convenient, the enhanced for loop has limited applications. It can only be used to iterate an entire array, not part of an array, and the declared integer variable cannot be used as an integer variable within the loop, only to refer to each element of the array. Copying an Array An assignment statement such as second = first; will not copy an array; it copies the reference to the array, creating two variables referencing the same array. To copy an array in Java, we must create another array of the same data type and size, then copy each value from the original array into the new array. The actual copying can be done with a for loop or with an enhanced for loop.
  • 127. Example 11 – copying an array // an array initialized with ten prime numbers int[] first = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; // To copy an array, we need to create another array of the same data type and size. int[] second = new int[10]; // Then, we copy each element from the first array into the second array. for(int i : i < first.length; i++) second[i] = first[i]; // This could also be done with an enhanced for loop for(int i : first)
  • 128. second[i] = first[i]; Arrays as Method Parameters in Java An entire array can be passed as a method parameter, but remember, the name of the array by itself is a reference to the base address where the array is stored in memory. It is this reference, and not the values in the array, that is passed to another method when an array is passed in Java. We end up with two different reference variables pointing to the same array in memory, not two different arrays, as shown in example 12 on the next page. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 14 Example 12 – Passing an Array as a Parameter
  • 129. In this example, an entire array is passed from the main method to the method printJob(). However, the array is not really passed; it is the value of the reference variable that points to the array’s location in memory that is really passed. Java always passes values. In this case the value is the address of the array in memory, so we end up with two different variables, priority – the original name for the array – and category – the copied name – both referring to the original array. variables symbol table memory map priority = new int [6]; priority 4000 4000 priority [0] int score; score 4018 4001 . . . 4002
  • 130. int[] category; category 4000 4003 int i; i 4054 4004 priority [1] int[] priority = new int[6]; . . . // call method printJob() printJob(priority); . . . public static void printJob(int[] category){ for( int i=0; i < category.length; i++) { System.out.printl(“Job” + i + “is in category “ + category[i]); . . . } The method header for the printJob() method establishes a reference variable to refer to an array, category, but category has no value until the method is invoked
  • 131. from another method. When printJob() is invoked from the main method, the value of the array reference variable priority is passed to array reference variable category in the formal parameter list. Now both priority and category have the same value, the address of the same array. This means they refer to the same array – priority and category have become two names for the same array – whatever we do to one we do to the other. If we change the value of an element in category we also change the value of that element in priority. category[3], for example, is priority[3]. Java always passes a value, not a reference to a value, but that value may be an address of an object, such as the address of the array passed in this case. 4005 4006
  • 132. 4007 4008 priority [2] 4009 400A 400B 400C priority [3] 400D 400E 400F 4010 priority [4] 4011 4012
  • 133. 4013 4014 priority [5] 4015 4016 4017 4018 score 4019 401A 401B 401C 401D 401E 401F
  • 134. 4020 The value of the actual parameter priority is passed to the formal parameter category, but that value is a reference to an array. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 15 Passing an Array Element as a Method Parameter Each element in an array is an individual variable that is treated like any other any variable with the element’s data type. It may be used like any other variable of
  • 135. that data type, including as an actual parameter for a method. Example 13 – passing an array element as a parameter In this example, price[] is an array of double values. price[3] in the main method is used as an actual parameter. The value of the variable price[3] is passed to the formal parameter cost when the method is invoked. double[] price = { 1.99, 3.87, 4.95, 2.99, 2.57}; . . . // all of the code is not shown currentSale(price[3]); . . . // all of the code is not shown /**************************************************** ******************/
  • 136. public static void currentSale(double cost) { System.out.printl(The cost of the item is: “ + cost); . . . // all of the code is not shown } The value of price[3] is copied to cost in the method currentSale(). Any change that is later made to cost has no effect on the original value in price[3]. CheckPoint 6.2 1. A one-dimensional array in Java is defined as an indexed fixed-length homogeneous data structure. What does this mean? 2. What is actually in an array if the array’s data type is a primitive data type and how does this
  • 137. differ from what is in an array if the array’s data type is class of objects? 3. What are the two ways that a value can be assigned to an array element? 4. Create an example showing how the enhanced for statement can be used to iterate an array. 5. How is an entire array passed as a method parameter and what happens in the original array if a value is changed in an array within a method that has received the array as a parameter? JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 16 Operations on Numeric Arrays Once we have a set of numbers stored in an array, we can
  • 138. perform numerical analysis of the data. Common operations on numerical arrays include finding the sum, the average, the minimum and the maximum of the values in an array. The following examples show how to do each of these things for a set of values in a double array. Sum, Average, and Count of Values in an Array To find the sum of a set numbers in an array we need a variable to hold the sum. It should have the same data type as the elements of the array, and it should be initialized to zero. Then, we iterate the loop, adding each value in the array to the sum, as in the following code. After the loop to iterate the array is finished, then the variable will hold the sum. The average is simply the sum divided by the number of elements in the array. The array length
  • 139. property is the number of elements in the array. Example 14 – finding the sum and average of values in an array double[] cost = new double[100]; // an array of 100 numbers double sum = 0; // the statements that give values to the elements in the array are not shown for(int i= 0; i < cost.length ; i++) sum = sum + cost[i]; System.out.println("the total cost is " + sum); System.out.println( "the average cost is " + sum/cost.length ); In this example, the average is calculated as part of the print statement. We could also have a variable to hold the average if we need to use it later.
  • 140. Counting Elements in an Array Sometimes we wish to count all of the values in an array that meet a certain condition. To do so, we simply initialize a counter to zero, then increment the counter for each element that meets the condition. Example 15 – counting the elements in an array In this we will again use the first ten Fibonacci numbers. Instead of printing each of the numbers, we will only print the even Fibonacci numbers and we will count them as well. The variable countEven is first initialized to zero, then, as we iterate the array, we will increment the count for each even Fibonacci number. To test for even numbers, we will use the Java’s remaindering
  • 141. operation (%), which returns the remainder of an integer division operation. If the remainder is zero when we divide by two, then the number is an even number. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 17 int[] fib = {0,1,1,2,3,5,8,13,21,34}; // an array initialized with Fibonacci numbers int i;// used as an array index int countEven = 0;// used to count how many of the first 10 Fibonacci numbers are even System.out.println(“Even Fibonacci numbers” ); // this loop prints the values in the array
  • 142. for( i= 0; i < fib.length ; i++) if (fib[i] % 2 == 0) { countEven++; System.out.println( fib[i] + “ is even”); } System.out.println ( countEven + “ of the first 10 Fibonacci numbers are even”); The output looks like this: Even Fibonacci numbers 0 is even 2 is even 8 is even 34 is even
  • 143. 4 of the first 10 Fibonacci numbers are even. The Minimum and Maximum Values in an Array To find the minimum value in an array, we start with a variable to hold the minimum. We initialize the minimum to the first value in the array, then go through the rest of the values in the array, testing each to see if it is less than the minimum. If a value is less than the minimum, it becomes the new minimum. After going through the entire array, the variable will hold the minimum value from the array. The maximum is calculated in almost the same way, setting the first value to be the maximum, except we then check to see if each value is greater than the maximum. Example 16 – finding the minimum value in an array double[] cost = new double[100]; // an array of 100 numbers
  • 144. int i; double minimum; // the statements that give values to the elements in the array are not shown minimum = a[i]; for( i= 1; i < cost.length ; i++) // iterate starting at the second element if ( cost[i] > minimum ) minimum = cost[i]; System.out.println("the minimum cost is " + minimum); Example 17 – finding the maximum value in an array double[] cost = new double[100]; // an array of 100 numbers int i;
  • 145. double maximum; // the statements that give values to the elements in the array are not shown maximum = a[i]; for( i= 1; i < cost.length ; i++) // iterate starting at the second element if ( cost[i] < maximum) maximum = cost[i]; System.out.println("the maximum cost is " + maximum); JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 18 Searching and Sorting Arrays Comparing Strings
  • 146. In order to search or sort an array of Strings we need to be able to compare String values. This is easy for integers and floating point data, but when it comes to Strings, there is a complication. The Boolean condition (a == b) will work if a and b are Strings, but it doesn’t work the way most people think it does. Strings are objects, and a comparison of two objects using the == operators compares the reference values stored in the two variables, not the values of the objects themselves. In other words, (a==b) will be true only if a and b refer to the same object, not equal objects. We have a similar problem with the < and > operators. Java has a number of different ways to compare objects in general and Strings in particular. Here we will look at two different methods from the String class that can
  • 147. be used to compare Strings: 1. the a.matches(b) method. The String matches() method returns a true value if the String variable a is equal to the String expression b, otherwise, it returns a false value. The String expression may be a variable, a String literal, or anything that evaluates to or returns a String. 2. the a.compareTo(b) method. The String compareTo() method compares two Strings lexicographically. A lexicographic comparison compares two text items character-by-character using a predefined collating sequence. In the case of Java Strings, the collating sequence is the UTF-16 version of Unicode. This is similar to the way a person might compare two names to see which one comes first alphabetically. The method returns an integer value,
  • 148. a. If the two Strings are the same, then the compareTo() method returns the integer 0. b. If a is less than b, then the method returns an integer less than 0 (a negative integer). c. If a is greater than b then the method returns an integer greater than 0 (a positive integer). The String matches() method is an easy way to see if two Strings are the same. The String compareTo() method is useful for when we are trying to see which String comes before the other, such as when we are sorting a list of String values. String handling is covered more in detail later in this course, and in subsequent courses. The matches() and compareTo() methods are used in the rest of this section.
  • 149. Linear Search of an Array Sometimes we wish to search an array to see if it contains a certain value. We can do this many different ways, but the simplest and most straightforward is a linear search. In a linear search of an array, we look at each value in the array one at a time to see if the value we are seeking is in the array. If we find the value, then we are done. If we get to the end of the array without finding the value, then the value is not in the array. There are several different ways to implement a linear search. We will use a loop with a compound condition and a Boolean variable to keep track of whether or not the value we are seeking is in the array. In the following example, we first look at the pseudocode for the array then see the final program
  • 150. built from that pseudocode. JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 19 Example 18 – linear search of an array In this example, an array contains a list of cities that have professional football teams. The user enters the name of a city to see if it is in the list. The program will perform a linear search of the array. First, a boolean variable named found is set to false. The continuation condition in the for loop to iterate the array will contain a compound condition, continuing while found is false and while the end of the array has not been reached. If the city is found, a message is printed and a boolean variable is set to true to terminate the loop. If the found variable is still false after the
  • 151. loop, a not found message is printed. Using the found variable in the compound condition provides an advantage by making the search more efficient. With it, the loop will stop as soon as the value is found. Without it, the loop always goes through the entire array. Consider, for example what happens if the value being sought is in the first element in an array of 100 elements. With the compound condition, the loop stops after looking at the first element. Without the compound condition the loop iterates all 100 times. The efficiency of algorithms is important, especially as data sets grow larger. Algorithmic efficiency is studied in detail CSCI 112 and 211. Pseudocode for a linear search of a String array /* in the search, n is the loop counter -- the continuation
  • 152. condition is: ( n less than NFLcities.length )and (target city not found) */ String[] NFLcities; // an array holding the names of cities with NFL teams n int; // loop counter boolean found = false; // will be set to true if the city is found in the list print intro message get the target name of the city from the user for ( i=0; not (found) AND n < NFLcities.length ; n++) if ( target matches NFLcities[n] ) // if the name entered matches this entry in the list. print NFLcity[n] has an NFL team set found to true
  • 153. after the loop – if not(found) print “ [target] is not in the list of cities with an NFL team.” JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 20 /* CSCI 111 - Fall 2013 * NFL City Search Program * This program performs a linear search of a String array with * the names of cities that have NFL teams * last editied Sept. 28, 2013 by C. Herbert */ package nflcities; import java.util.Scanner;
  • 154. public class NFLcities { public static void main(String[] args) { // an array holding the names of cities with NFL teams. String[] NFLcities = {"Buffalo", "Miami", "Boston", "New York", "Baltimore", "Cincinnati", "Cleveland", "Pittsburgh", "Houston", "Indianapolis", "Jacksonville", "Tennessee", "Denver", "Kansas City", "Oakland", "San Diego", "Dallas", "New York", "Philadelphia", "Washington", "Chicago", "Detroit", "Green Bay", "Minnesota", "Atlanta", "Charlotte", "New Orleans", "Tampa", "Arizona", "St. Louis", "San Francisco", "Seattle"};
  • 155. String target; // the city for which we are searching int n; // loop counter boolean found = false; // true if the target city is found in the array // set up input stream from the keyboard Scanner keyboard = new Scanner(System.in); // print intro message System.out.print("This program will tell you if a city has an NFL team.nn"); // get the target name of the city from the user System.out.print("Please enter the name of a city: " );
  • 156. target = keyboard.nextLine(); // search array of NFL cities for target city // the loop coninues to the end of the array if the city is not found for (n=0 ; (!found) && (n < NFLcities.length) ; n++) { if (NFLcities[n].matches(target) ) // uses the String class matches() method { //print found message and set found to true System.out.println(target + " has an NFL team.n"); found = true; } // end if
  • 157. } // for loop // after the loop – if not(found) print not found message if (!found) System.out.println(target + " is not in the list of cities with an NFL team.n"); } // end main() } // end class JLK Chapter 6 – Arrays DRAFT 2015 Edition pg. 21 Sorting an Array It is useful to be able to sort an array. There are many different
  • 158. ways to do so, which are studied in detail in CSCI 112 and CSCI 211. We will look at a simple sorting method called a bubble sort. In a bubble sort, we go through an array of data comparing each data item to the next item. If they are out of order, then we swap them; if they are in the correct order, then we leave them alone. We compare each item to the next item until we reach the end of the array. Each time we go through the entire array is called a pass through the array. We continue to make passes until we can make one pass all the way through the array without swapping anything. The bubble sort is based on the transitive property of equality and inequality (if A≤B and B≤C, then A≤B) If we can make a pass without swapping anything, then we know the array is in the correct order and we’re done – the array is sorted.
  • 159. We can use a boolean variable named swapped to keep track of whether or not we needed to swap anything in each pass through the array. Before we go through the array, we set swapped to false. If we swap anything, we also set swapped to true. When we finish a pass, if swapped is true, then something was swapped, and another pass is needed. If swapped is still false after making a pass through the array, then nothing needed to be swapped in that pass, and the array is in the correct order; the sort is done. Here is pseudocode for a bubble sort of an array. Notice that each pass through the array only goes to the second-to-last element in the array, since we are comparing each element to the one that follows it. The last comparison will then be between the second-to-last element in the array and the last element.