Subroutines
Material from Chapter 5
Flow of Control
Sequence
Selection
Repetition
Subroutine
Sequence Review
Each command in the order it appears
a
b
c
a
=
=
=
=
5;
6;
a * b;
7;
//
//
//
//
//
a is now 5
b is now 6
c is now 30 (5*6)
a changed to 7
(but c is still 30)
Selection Review
Choose between commands to execute
hrs = keyboard.nextInt();
if (hrs <= 40) {
pay = hrs * rate;
} else {
pay = (hrs + (40-hrs)*1.5) * rate;
}
System.out.println(“Pay for ” + hrs
+ “ hours is ” + pay);
Repetition Review
Execute commands multiple times
resp = keyboard.next().toUpperCase();
while (!resp.equals("YES")
&& !resp.equals("NO")) {
System.out.print("Yes or no? ");
resp = keyboard.next();
}
// resp now either YES or NO
Subroutine
One step of main algorithm
Details listed separately
…
while there are lug nuts:
» Remove a lug nut
…
To remove a lug nut:
» ...
Reasons For Using Subroutines
Code Re-use
Doing “same” thing in multiple places
Code Hiding (Encapsulation)
Secret
Implementation independence
Code Abstraction
Top-down design
»
Make each part of program smaller & easier to read
Subroutines in Java
Java subroutines are called methods
something an object knows how to do
attached to an object (or class)
We have already used methods
System.out.println is a method
keyboard.nextInt is a method
main is a method (static method — more later)
Flow of Control
You ask System.out to print “Hello”
computer stops working on your program (for a
moment) & takes “Hello” to the print method
the steps of the print method are followed to
completion Hello appears on the screen
your program starts up again, right where it left
off
Something you send to a subroutine
(like “Hello”) is called an argument
Flow of Control
You ask keyboard to get the next int
computer stops working on your program (for a
moment) & starts doing the nextInt method
the steps of the nextInt method are followed to
completion, getting an int from the user
that int is brought back to your program
your program starts up again, right where it left
off, with the int that keyboard.nextInt sent back
to you
Something a subroutine sends back to
you (like this int) is called a return value
Using an Existing Method
Someone has written down the algorithm
for reading an integer — made a method in
the class Scanner
they put Scanner somewhere you can get to it
(java.util library/package)
you get it (import java.util.Scanner)
make a Scanner object (Scanner k = new …)
ask that object to read an integer (k.nextInt())
Using Existing Methods
Using System.out.println is even easier
System.out is an object already
don’t need to tell Java you’ll be using it
Strings have methods, too
can ask resp (a String object) whether it’s
equal to “YES” (ignoring case) – it knows how
to check (someone wrote that algorithm)
Need an object; usually need to make one
Classes for Methods
Scanners know how to do input
PrintStreams knows how to print stuff
System.out is a PrintStream object
Strings know how to do things, too
So far we’ve only created one method in
each class we’ve made: main
does all the stuff our program knows how to do
Creating Our Own Methods
Break our program into smaller pieces
main method is in control
calls other methods in the same program
we make those other methods
can still call methods from other classes
Can make classes that have no main method
just a collection of related methods
String, Scanner, PrintStream are like that
GreesieBurger, Again
Has loop to make sure answer is yes or no
while (!resp.equals("YES")
&& !resp.equals("NO")) {
can extend it to accept more answers:
while (!resp.equals("YES")
&& !resp.equals("OK")
&& !resp.equals("SURE")
&& !resp.equals("NO")
&& !resp.equals("NOPE")) {
code is getting hard to read!
Note: the if control to check if it’s yes needs to be updated, too!
GreesieBurger, Again
Create a method to check the answer
while (notYesOrNo(resp)) {
let the method hide all the details
Do the same for checking whether it’s yes
if (isYes(resp)) {
System.out.println("FRIES!");
System.out.println("(fries)");
price += 2.99;
}
Quick Way to Create Method
Ask NetBeans to do it for you
cannot find symbol method notYesOrNo error
click on red dot
select Create method notYesOrNo(…) in …
» there might be more than one of these
» choose the one that uses the current class
NetBeans creates a method for you
» unfortunately it just crashes your program…
Quickly Created Methods
NetBeans’ method will look like this:
private static boolean notYesOrNo(String resp) {
throw new UnsupportedOperationException(…);
}
replace throw command with return command
» after return write the stuff you cut out of the if
return !resp.equals("YES")
&& !resp.equals("OK")
&& !resp.equals("SURE")
&& !resp.equals("NO")
&& !resp.equals("NOPE");
I’ll explain return soon.
Repeat with isYes method
Starting from:
if (resp.equals("YES")
|| resp.equals("OK")
|| resp.equals("SURE")) {
…create this method:
private static boolean isYes(String resp) {
return resp.equals("YES")
|| resp.equals("OK")
|| resp.equals("SURE");
}
I’ll explain the rest of the method definition, too. Eventually.
Benefits
Code in main is shorter and easier to read
also easier to understand
Can use them for other yes-no questions
don’t need to write all that code down again
System.out.print("Would you like a drink? ");
drinkAnswer = kbd.next().toUpperCase();
kbd.nextLine();
while (notYesOrNo(drinkAnswer)) { … }
if (isYes(drinkAnswer)) { … }
Arguments
The bits that go inside the parentheses
can be different each time you call the method
System.out.print("The sum is ");
System.out.print(sum);
while (notYesOrNo(friesAnswer)) { … }
while (notYesNo(drinkAnswer)) { … }
method will use whatever argument you give it
» as long as it’s the right kind of argument
» (the right data type)
How Does it Work?
Same way all the other methods do!
computer stops working on your program (for a
moment) & starts the isYes method
the steps of isYes are followed to completion,
getting a boolean value at the end
that boolean value comes back to your program
your program starts up again, right where it left
off, with the boolean that isYes sent back to
you
Compare
Our main method definition
public static void main(String[] args) { … }
Our isYes method definition
private static boolean isYes(String resp) { … }
Different:
“public” vs. “private”
“void” vs. “boolean”
“main” vs. “isYes”
“String[] args” vs. “String resp”
what’s inside the braces (bodies)
Same:
“static”
parentheses
braces
public vs. private
public = any class can call this method
private = can only be called from this class
Can call main from any other class:
public class Week05 {
public static void main(String[] args) {
System.out.println(“We’re going to Greesie’s!”);
GreesieBurger.main(args);
System.out.println(“That was yummy!”);
}
This is Week05.main calling GreesieBurger.main.
}
If the method is in another class, you have to say that class.
void vs. boolean
Return type of method
data type of the value it returns
» boolean returns true or false
» void doesn’t return anything
can return any kind of value
private static String authorID() {
return "Mark Young (A00000000)";
}
private static int myAgeIn(int year) {
return year – MY_BIRTH_YEAR;
}
Of course, need to return same type you said you would!
main vs. isYes
Method names look like variable names
camelCase, starting with small letter
Method name says what it does or returns
isYes returns whether the String you give it is
equivalent to “yes”
notYesOrNo returns whether the String you
give it is NOT equivalent to “yes” or “no”
myAgeIn returns my age in a given year
main is a special name—Java needs it to be named that.
String[] args vs. String resp
Inside parentheses after the name
in the method call: an argument
» can be any value of the right data type
in the method definition: a parameter
» a variable to hold the argument value
isYes and notYesOrNo both expect a String
» resp is set to whatever String was in the call
» isYes("ok"), isYes("nope"), isYes("what?")
main expects a String[] – but we just ignore it!
I’ll explain about String[] near the end of term.
Arguments and Parameters
Important to keep these straight!
argument is in method call
if (isYes(drinkYesNo))
parameter is in method definition
private static boolean isYes(String yesNo)
argument is often a variable
parameter is always a variable declaration
» it's an entirely different variable than the argument
» even if it has the same name as the argument!
And the argument is never a variable declaration!
Method Body
Difference between main and other methods
main is doing the main job (duh!)
other methods only do a small part of it
Not unusual for other method to be one line
or one long command spread over many lines
For now, main will be long, other methods
will be short
that’s because our programs are so small (!!!)
Method Design
Make the method’s job a small one
check whether a String means yes
check whether a String means no
Give it a name that reflects that job
Determine its return type
what kind of a thing is its answer?
Determine its argument type(s)
what kind of a thing is it being asked about?
Return Types
What kind of value does the method return?
look at where the value gets put
int n, m;
double x, y;
String resp;
boolean wantsFries;
n = kbd.nextInt();
y = kbd.nextDouble();
resp = kbd.next();
wantsFries = isYes(resp);
// in an int variable
// in a double variable
// in a String variable
// in a boolean variable
Return Types
What kind of value does the method return?
look at where the value gets used
(what kind of value do we need here?)
if ( resp.startsWith( getBase() ) )
// startsWith needs a String value
// getBase must return String
if ( isYes(resp) )
// if needs a boolean value
// isYes must return boolean
Return Types
Some methods don’t return anything!
System.out.print(“This”);
System.out.println(“That”);
no answer to save in a variable
answer = System.out.println(“No way!”);
// incompatible types: void can’t be converted to String
no answer to use in a larger command
if ( System.out.println(“Nonsense!”) ) { … }
// incompatible types: void can’t be converted to boolean
Exercise
The code below is correct. What kind of
value does each bolded method return?
double x = 3.2, y;
int n = 42, m;
String name = “Mark”;
name = name.replaceFirst(“a”, “o”);
y = Math.pow(x, 2);
m = Math.min(n, 100);
if (name.equalsIgnoreCase(“mork”)) {
System.out.println(“Nanoo-nanoo!”);
}
Argument Type(s)
What goes inside the parentheses?
resp.startsWith(“yes”)
// a String
Math.sqrt(10.0)
// a double
Math.pow(x, 2.0)
// two doubles
kbd.nextLine()
// nothing(!)
kbd.findWithinHorizon(“no”, 20);
// String and int
Can have any number of arguments
must be same as number of parameters
must be in same order as parameters
Argument Types
Arguments must be the right type!
Math.pow(“fred”, true) makes no sense!
» the two arguments must be numbers
» doubles are OK: Math.pow(3.7, 1.98)
resp.startsWith(7) makes no sense!
» the argument must be a String: resp.startsWith(“7”)
There must be the right number of them!
» Math.pow(5) and Math.pow(1, 2, 3) make no sense!
and they must be in the right order
Exercise
Assume the calls below are correct. What
argument type(s) does each method take?
Math.getExponent(3400.2)
Math.ulp(2.6)
Math.scalb(4.5, 2)
str.split(“:”, “one:two:three:four”)
str.length()
str.regionMatches(true, 0, “this”, 7, 50)
Classes with Public Methods
Some classes are not programs at all
They are just collections of related methods
Math collects basic numeric operations
x = Math.sqrt(y);
tax = Math.max(basicTax, alternativeTax);
z = Math.hypot(x, y);
sodium = Math.abs(sodium);
x2 = x1 + length * Math.cos(theta);
area = Math.PI * Math.pow(radius, 2);
Math Functions
Standard functions available using Math
power function: pow
System.out.println(“5 squared is ” + Math.pow(5, 2));
maximum function: max
int max = Math.max(n1, n2);
square root: sqrt
double root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);
Same form for all functions
Math.functionName(arguments…)
Arguments
“Arguments” are given to the method
» we also say that the method takes arguments
Math.sqrt(10) – 10 is the (only) argument
» asks Math for the square root of 10
Math.pow(5, 2) – 5 and 2 are both arguments
» asks Math for 5 to the power 2 (i.e. 52)
arguments must be in the right order!
» Math.pow(2, 5) is 25, not 52
Return Values
Methods return values
» (but some don’t)
we use the function to get the returned value
Math.sqrt(10) returns the square root of 10
Math.pow(2, 5) returns 2 to the 5th power
Math.pow(5, 2) returns 5 to the 2nd power
Math.sqrt(x) returns the square root of x
Name of method == what value is returned
Using Math Functions
Use the function in expressions
you can print it out
System.out.println(“5 squared is ” + Math.pow(5, 2));
you can save the value in a variable
maxGrade = Math.max(maxGrade, grade);
you can use it in a larger math expression
root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);
» and the argument can be an expression, too!
Using Return Values
Use the function in expressions
return value used in the expression
System.out.println(“5 squared is ” + Math.pow(5, 2));
» Math.pow(5, 2) returns 52 = 25.0
» System.out.println prints “5 squared is 25.0”
root = (-b + Math.sqrt(b*b – 4*a*c)) / (2 * a);
» suppose a is 1, b is 6 and c is 9
» b*b – 4*a*c = 6*6 – 4*1*9 = 36 – 36 = 0
» Math.sqrt(0) returns 0.0
» root = (-6 + 0.0) / (2*1) = -6.0 / 2.0 = -3.0
Some Math Functions
Trigonometric functions
sin, cos, tan
» each takes an angle (measured in radians)
toDegrees, toRadians
» toDegrees takes an angle measured in radians,
toRadians takes an angle measured in degrees
Exponential & logarithmic functions
exp, log, sqrt
» each takes a number (a double value)
Exercise
Write calls to Math functions to find
the square root of 7
6 to the 3rd power
10 times the log of x
the log of 10 times x
the number of radians equivalent to 45 degrees
the sine of 45 degrees
More Math Methods
Larger & smaller; rounding off
max, min
ceil, floor, round
(each takes two numbers)
(each takes one number)
Random number (in range [0,1))
random
int dieRoll1 = 1 + (int)(Math.random() * 6);
int dieRoll2 = 1 + (int)(Math.random() * 6);
int dice = dieRoll1 + dieRoll2;
Note: random takes no arguments! That’s fine.
Rounding Off
Math.round takes a double, returns a long
Math.round(3.0) 3L
» long is like int, but bigger (up to ~10 quintillion)
can’t be saved in an int variable!
int rounded = Math.round(3.6);
» Error: possible loss of precision
need to tell Java it’ll be smaller…
int rounded = (int)Math.round(3.6);
» or just work with long variables!
Exercise
Write these math expressions in Java
x5 – 1
y=
x–1
a = πr2
z=
density = mass / volume
» rounded to nearest int
» mass and volume are doubles
User-Defined Method Classes
Math was created because it's useful
someone wrote each of those methods
put it all in a class named Math
made Math available to everyone
We can make our own useful classes
create multiple (related) methods
put all in a class
make that class available to others
Example Class: Converter
A class for objects that know how to
convert between metric and imperial/US
measurements
use it like this:
double degreesF, heightInCM;
degreesF = Converter.celsiusToFahrenheit(29.0);
System.out.println(“29C = ” + degreesF + “F”);
hgtInCM = Converter.feetInchesToCM(5, 8);
System.out.println(“5’ 8\” = ” + hgtInCM + “cm”);
Converter Class Definition
public class Converter {
public static double celsiusToFahrenheit(double degC) {
return 32.0 + 9.0 * degC / 5.0;
}
public static double feetInchesToCM(int f, double in) {
return 2.54 * (12.0 * f + in);
}
We should make CONSTANTS for
…
the numbers we’re using here…
}
More methods will be added later
Flow of Control
degreesF = Converter.celsiusToFahrenheit(29.0);
84.2
degreesF
(uninitialized)
84.2
degC
Converter
public static double celsiusToFahrenheit(double degC) {
return 32.0 + 9.084.2
* degC / 5.0;
}
public static double feetInchesToCM(int f, double in) {
return 2.54 * (12.0 * feet + inches);
}
29.0
Subroutine Body
public double celsiusToFahrenheit(double degC) {
return 32.0 + 9.0 * degC / 5.0;
}
return = this is what to send back
calculate the value of the expression
the same type as what you said it would be
Not unusual for a function to be just one line
not unusual for it to be more than one line!
use as many lines as you need to say what to do
The return Command
Tells method what value to send back
the value the method returns!
return 3.5; // returns a double value //
return 7; // returns an int value //
return “Hello!”; // returns a String value //
or, more likely,
return result;
where result has the value we calculated
» e.g. the number of Fahrenheit degrees
Position of the return Command
The return command is at the end
when function returns a value, its job is done
» it will not do anything after that
so no code comes after a return command
» error message: unreachable statement
» another error message: missing return command
next thing after a return command must be a }
» nothing else makes sense!
Method Body
Anything you can do in main…
…you can do in a subroutine
variable declarations
assignment statements
selection controls (if, switch)
repetition controls (while, do-while, for)
subroutine calls
(other things we haven’t learned about yet)
Subroutine Body
public static double celsiusToFahrenheit(double degC) {
double degF;
degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
This body has three lines
first line is a local variable declaration
second line is the calculation
third line is the return command
Subroutine Body
public static double celsiusToFahrenheit(double degC) {
double fahrDegrees, fahrTemp;
fahrDegrees = 9.0 * degC / 5.0;
fahrTemp = fahrDegrees + 32.0;
return fahrTemp;
}
This body has four lines
different variables than last version
but still does same job: convert °C to °F
On Local Variables
Any variables you declare in a subroutine
stay in the subroutine
no other subroutine can use them
(it’s like they’re in a different room – or a
different house)
in particular, main cannot use those variables!
main doesn’t even know what local variables
the subroutine has! degF? fahrTemp?
neither?
Exercises
Write Converter methods
fahrenheitToCelsius
subtract 32, then multiply by 5 and divide by 9
68 – 32 = 36; 36 * 5 / 9 = 180 / 9 = 20
68F = 20C
cmToInches
divide by 2.54
100 / 2.54 = 39.37
100cm = 39.37”
Class Commentary
Comments for helper class like comments
for program – appear after import
commands, just before class declaration
/**
* A class for converting between metric and
* imperial/US measures
*
* @author Mark Young (A00000000)
*/
Method Commentary
Methods (not main) get similar comments
/**
* Convert Celsius to Fahrenheit
*
* @param celsius temp in Celsius
* @return
same temp in Fahrenheit
*/
brief description of method
each parameter named and described
return value described
(author if different from class)
Input & Output
Value-returning methods usually do NONE
common mistake is to have it ask for the value
to use – but we already gave it that value
celsiusToFahrenheit(29.0)
common mistake is to have it print the answer –
but what if main doesn’t want it printed?
tempInCelsius = celsiusToFahrenheit(29.0);
just do the math; leave caller to do the I/O
Bad Behaviour
double tempC;
tempC = BadConverter.fahrenheitToCelsius(32.0);
System.out.println(“32.0F = ” + tempC + “C”);
What temperature would you like to convert? 50
50.0 degrees Fahrenheit is 10.0 degrees Celsius
32.0F = 10.0C
What went wrong?
32F = 0C
fahrenheitToCelsius got “creative” (did I/O)
Parameter Values
Parameter gets its value from method call
celsiusToFahrenheit has a parameter: degC
called: Converter.celsiusToFahrenheit(29.0)
degC is assigned the value 29.0
Where did the 29.0 come from?
WE DON’T CARE!!!!
» it’s somebody else’s problem!
our job is not to choose what to convert
our job is to convert what we’re given
Questions
© Copyright 2026 Paperzz