CHAPTER 5-1
METHODS
A method is a construct for grouping statements together to perform a well-defined function.
For example, often we need to find the maximum between 2 integers. We can do 1 of 2 things:
1. Whenever we need this function, we write something similar to the following code:
int result;
if (num1 > num2) result = num1;
else result = num2;
2. Define a method, say max, which finds the maximum between 2 numbers. Whenever we need to
find the maximum between 2 numbers, we simply call max.
It should be obvious that approach 2 is a much better approach. Of course, we should be able to call
max to find the maximum between num1 and num2, or between i and j, or between x and y, or
between any 2 numbers we want. Since the max method is written only once, and it does not know
which 2 numbers the caller will pass it, its algorithm operates on _______ arguments. These dummy
arguments will be replaced by the ______arguments passed to the method when the method is invoked.
…
x=MyLib.max(num1,num2);
…
…
y= MyLib.max(n1, n2);
…
num1,num2
n1,n2
result
result
public class MyLib
{
public static int max(int x, int y)
{
int result;
if (x > y) result = x;
else result = y;
return result;
}
}
Method definition revisited
In Java, we define a method inside a class construct, similar to defining method main.
Here is the method definition syntax (items enclosed by square brackets are optional):
[accessSpecifier] [static] returnType methodName([type1 dummy1, type2 dummy2, …])
{
data definition statements
//Define local variables
data manipulation statements
//Manipulate dummy arguments and local variables
[return statement]
//Return a value as well as control to the caller
}
//If there is no return statement, this closing curly
//bracket, when reached, returns control to the caller
//Example 5-1-1
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.println("Hello");
}
public static void printName()
{
System.out.println("John Johnson");
//line 5
//line 6
//line 7
//line 8
//line 9
//line 10
//line 11
}
}
//line 12
When Java executes a console program, it only executes method main (it only calls Demo.main).
A class can contain many method definitions. The order of the method definitions is insignificant.
Static Method call
A method definition merely defines how to perform an operation. The execution of a method
definition is not automatic. A method will not be executed unless it is ___________.
The syntax of a method call to a static method is:
className.methodName(actualExpr1, actualExpr2, …)
When Java executes such a method call expression, Java carries out the following actions:
1. The activation record of method className.methodName is created with 1 location for each
dummy argument defined in the method header.
2. The value of actualExpr1 is passed to dummy1, the value of actualExpr2 is passed to dummy2,
and so on (that is, the values of the actual arguments are used to initialize the dummy arguments).
3. Program control is transferred to the first statement in method className.methodName.
//Example 5-1-2
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.println("Hello");
Demo.printName();
System.out.println("Hello again");
}
public static void printName()
{
System.out.println("John Johnson");
}
}
//line 7
//line 8
//line 9
//line 10
//line 12
//line 13
If a method calls another method that is defined in the same class, we can simply use the method name
without the class name. Thus, we can replace line 8 by the following line:
printName();
Method that takes arguments
Consider the following method definition:
public static void f(int x, double y)
{
…
}
o To call f, we must pass it 2 actual arguments, ________ and ________, in that order.
o An actual argument can be any legal Java expression as long as it is of the same type as its
corresponding dummy argument. It is the value of an actual argument that is passed.
When we formulate a method call to invoke a method, the number of actual arguments must be the
same as the number of dummy arguments, and the corresponding arguments must have the same type.
Suppose that j is an int, and d is a double.
f (j, d)
f (j, 3.4)
f (5*3, Math.sqrt(2.2))
f ()
f (j)
f (j, d, j)
f ("Hello", "There")
f ("Hello", true)
Java performs automatic type conversion when passing arguments to a method. In particular, Java will
convert the value of an actual argument to the type of its corresponding dummy argument if it involves
a promotion, and Java will report an error if it involves a demotion.
f (5, 5)
f ('a', j)
f (5.5, 5)
f (d, j)
The reason we pass arguments from the calling method to the called method is because a method can
only access the data items defined within its own definition (dummies or locals).
//Example 5-1-3
//Demo.java
public class Demo
{
public static void main(String[] args)
{
double points=78.5;
System.out.print("The grade is ");
}
public static void printGrade(double score)
{
if (score >= 90.0) System.out.println('A');
else if (score >= 80.0) System.out.println('B');
else if (score >= 70.0) System.out.println('C');
else if (score >= 60.0) System.out.println('D');
else System.out.println('F');
}
}
The return statement
The body of a method definition can contain 1 or more return statements. The syntax of a return
statement is:
return [Expr];
Here, return is a keyword, and Expr is a legal Java expression that is of the return type of its enclosing
method. Note that if the return type of the enclosing method is void, then Expr must be absent.
When the computer executes a return statement, it carries out the following actions:
1. Evaluates Expr if Expr is present.
2. Destroys the method's activation record.
3. Returns control to the method call in the caller, along with the value of Expr if present.
//Example 5-1-4
//Demo.java
public class Demo
{
//Output: The sum of 10, 11, and 12 printed on the screen
public static void main(String[] args)
{
int sum=0;
//line 9
sum=findSum(10, 11, 12);
System.out.println("Sum is "+sum);
}
//Return: The sum of n1, n2, and n3
public static int findSum(int n1, int n2, int n3 )
{
int result=0;
result=n1+n2+n3;
return result;
}
//line 10
//line 11
//line 17
//line 18
//line 19
}
Walkthrough:
The Java interpreter calls main. After the Java interpreter has called main, main's activation record has
the following state:
main's activation record
args: ?
After line 9 is executed, main's activation record has the following state (sum has been allocated and
initialized):
main's activation record
args: ?
sum: 0
Then line 10 executes. After the method call is executed, here is the program state:
main's activation record
findSum's activation record
args: ?
n1: 10
sum: 0
n2: 11
n3: 12
Then line 17 of method findSum executes. After line 17 is done, we have the following program state
main's activation record
findSum's activation record
args: ?
n1: 10
sum: 0
n2: 11
n3: 12
result: 0
Then line 18 executes. After line 18 is done, we have the following program state
main's activation record
findSum's activation record
args: ?
n1: 10
sum: 0
n2: 11
n3: 12
result: 33
Then line 19 executes. After line 19 is done, we have the following program state:
main's activation record
args: ?
sum: 0
Then line 10 resumes its execution. After line 10 is done, we have the following program state:
main's activation record
args: ?
sum: 33
Then line 11 executes, which prints sum (33) on the screen.
Since line 11 is the last statement in method main and method main has no return statement, the Javasupplied return statement executes. Thus, main's activation record is destroyed and control is
transferred back to the JVM.
Note:
For the API of a main method, we typically include 3 comments: Description (a brief description as to
what the method does), Input (the input requirements), and Output (the output specifications).
For the API of other user-defined method, we include comments such as Description, Pre (conditions
on the operands), Post (side effects), Return (the return value), Input (the input requirements if the
method reads from the keyboard or disk files), and Output (the output specifications if the method
writes to the screen or disk files).
//Example 5-1-5
//Demo.java
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
System.out.print("Enter a signed integer: ");
Scanner f=new Scanner(System.in);
int n=f.nextInt();
if (sign(n)==1) System.out.println("You entered a positive integer");
else if (sign(n)==0) System.out.println("You entered 0");
else if (sign(n)==-1) System.out.println("You entered a negative integer");
}
//Return: 1 if n is positive, 0 if n is 0, -1 if n is negative
public static int sign(int n)
{
if (n>0) return 1;
else if (n==0) return 0;
else if (n<=0) return -1; //line 19
}
}
A return statement is required for a value-returning method.
//Example 5-1-6
//Demo.java
public class Demo
{
public static void main(String[] args)
{
System.out.print("The grade is ");
printGrade(178.5);
}
public static void printGrade(double score)
{
if (score <0||score>100)
{
System.out.println("invalid score");
return;
}
if (score >= 90.0) System.out.println('A');
else if (score >= 80.0) System.out.println('B');
else if (score >= 70.0) System.out.println('C');
else if (score >= 60.0) System.out.println('D');
else System.out.println('F');
}
}
A return statement is optional for a void method. Return statements in a void method cannot return a
value.
Methods which accept arguments are adaptable
//Example 5-1-7
//Demo.java
public class Demo
{
public static void main(String[] args)
{
printName("John Johnson");
printName("Peter Peterson");
}
public static void printName(String s)
{
System.out.println(s);
}
}
//line 7
//line 8
//line 12
//Example 5-1-8
//Demo.java
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
int sum=0;
sum=findSum(10, 11, 12);
System.out.println("Sum is "+sum);
sum=findSum(21, 22, 23);
System.out.println("Sum is "+sum);
System.out.print("Enter 3 integers separated by white space: ");
Scanner f=new Scanner(System.in);
sum=findSum(f.nextInt(), f.nextInt(), f.nextInt());
System.out.println("Sum is "+sum);
}
public static int findSum(int n1, int n2, int n3 )
{
int result=0;
result=n1+n2+n3;
return result;
}
}
//line 8
//line 9
//line 10
//line 11
//line 12
//line 13
//line 14
//line 15
//line 16
//line 20
//line 21
//line 22
Consider
public static void printMessage(String s, int n)
{
for (int i = 0; i < n; i++)
System.out.println(s);
}
1. Suppose you invoke the method using:
printMessage (“Welcome to Java”, 5);
What is the output?
2. Suppose you invoke the method using:
printMessage (“Computer Science”, 15);
What is the output?
//Example 5-1-9
//Demo.java
public class Demo
{
//Output: The max between 5 and 2 printed on the screen
public static void main(String[] args)
{
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i + " and " + j + " is " + k);
}
//Return: The max of n1 and n2
public static int max(int num1, int num2)
{
int result;
if (num1 > num2) result = num1;
else result = num2;
return result;
}
}
Case Study – Average of integers
//Example 5-1-10
//Average.java
import java.util.Scanner;
public class Average
{
//Desc: Compute the average of a sequence of integers
//Input: A sequence of integers entered via the keyboard separated by ws; 0 is the sentinel
//Output:The average of the input integers printed on the screen
public static void main(String[] args)
{
average();
}
//Input: A sequence of integers entered via the keyboard separated by ws; 0 is the sentinel
//Output:The average of the input integers printed on the screen
}
}
Method average is not well designed. A good software engineering practice states that a function
should do 1 task and only 1 task.
Case Study – Degree conversions
//Example 5-1-11
//DegreeConversion.java
public class DegreeConversion
{
//Output:86 degree Fahrenheit converted to degree Celsius and printed on the screen
//
32 degree Celsius converted to degree Fahrenheit and printed on the screen
public static void main(String[] args)
{
double fah=86.0;
double cel=32.0;
System.out.println(fah+"F"+"="+ fahToCel(fah) +"C");
System.out.println(cel+"C"+"="+ celToFah(cel) +"F");
}
}
The Math class
Class Math is in package java.lang.
---------------------------------------------------------------------------------------------------------------------------public final static double PI=3.14159265358979323846;
Usage: public static long round(double a)
Return: The value of the argument rounded to the nearest long value
Usage: public static double abs(double x)
Return: The absolute value of x (overloaded to support other data types such as float, int, long)
Usage: public static double sqrt(double x)
Return: The square root of x. Return NaN if x is negative.
Usage: public static double ceil(double x)
Return: The smallest integer as a double not less than x.
Usage: public static double floor(double x)
Return: The largest integer as a double not greater than x.
Usage: public static double pow(double a, double b)
Return: The value ab
Usage: public static double max(double a, double b)
Return: The greater of a and b (overloaded to support other data types such as float, int, long)
Usage: public static double min(double a, double b)
Return: The smaller of a and b (overloaded to support other data types such as float, int, long)
Usage: public static double random()
Return: A pseudorandom double value greater than or equal to 0.0 and less than 1.0.
---------------------------------------------------------------------------------------------------------------------------Figure 5-1-1. The API of some useful Math constants and methods.
//Example 5-1-12
//Demo.java
public class Demo
{
public static void main(String[] args)
{
double x=1.44;
double y=2.0;
System.out.println("Rounding " + x + " we have " + Math.round(x));
System.out.println("Absolute value of " + x + " is " + Math.abs(x));
System.out.println("Square root of " + x + " is " + Math.sqrt(x));
System.out.println("Ceiling of " + x + " is " + Math.ceil(x));
System.out.println("Floor of " + x + " is " + Math.floor(x));
System.out.println("Power of " + x + " to " + y + " is " + Math.pow(x, y));
System.out.println("Maximum of " + x + " and " + y + " is " + Math.max(x, y));
System.out.println("Minimum of " + x + " and " + y + " is " + Math.min(x, y));
System.out.println("A random number is " + Math.random());
System.out.printf("The area of circle with radius 2.0 is %.2f", Math.PI*2*2);
}
}
//Example 5-1-13
//Demo.java
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
System.out.print("Enter a real number: ");
Scanner input=new Scanner(System.in);
double x=input.nextDouble();
System.out.println(x+" rounded to 2 decimal places is " + ________________________);
}
}
The Java API Documentation
The Java API consists of a large collection of predefined classes. To find out how to use a class
provided by Java, the best way is to read its documentation. To download and install Java SE
Documentation on a Windows system, do the following:
a. On the same download page where you downloaded Java SE 8u121, scroll down and download
Java SE 8 Documentation, jdk-8u121-docs-all.zip.
b. Move the file jdk-8u121-docs-all.zip to where you want the documentation to be located on your
computer (e.g. C:\JavaDoc).
c. Open the Command Prompt window.
d. Change directory to the folder where the zip file is located by entering the following command in
the Command Prompt window (replace where by the absolute path of the folder where the zip file
is located):
cd where
(e.g. cd C:\JavaDoc)
e. Unzip the zip file using the jar utility that comes with Java SE 8u121 by entering the following
command in the Command Prompt window:
jar -xvf jdk-8u121-docs-all.zip
The jar command creates a folder named docs which contains the documentation.
To read the documentation, double click the index.html file in the docs folder:
Click on the link Java SE API on the right side of the page:
The lower left pane lists all classes in the java API in alphabetical order. Let us scroll down the list to
locate class Math. Let us click Math:
The right pane displays the documentation for class Math.
Let us click the link Method near the top of the right pane:
The right pane displays the documentation for the methods provided by class Math. We can then click
on a method to see its documentation.
Programming Exercises
1.
Write a console application which draws the following picture of the Big Dipper:
The main method MUST call 1 method:
drawDipper, which takes no argument and returns nothing. Method drawDipper prints the Big
Dipper on the screen.
Note:
2.
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//BigDipper.java
Write a console application which reads a radius from the keyboard and prints the circumference of a
circle with the input radius on the screen, as well as the volume of a sphere with the same radius on the
screen.
The main method MUST call 2 methods:
circleCircumference, which takes 1 argument (radius) and returns the circumference of the circle
sphereVolume, which takes 1 argument (radius) and returns the volume of the sphere
Note:
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//CircleSphere.java
3.
Write a console application which reads the top, base, and height of a trapezoid and prints the area of
the trapezoid on the screen.
The main method MUST call 1 method:
trapezoidArea, which takes 3 arguments (top, base, height) and returns the area of the trapezoid.
Note:
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//Trapezoid.java
Hint:
The area of a trapezoid is given by 1 height (top base)
2
4.
Write a console application which reads 3 integers and find their minimum and maximum.
The main method MUST call 2 methods:
findMin, which takes 3 int arguments and returns the minimum of the arguments.
findMax, which takes 3 int arguments and returns the maximum of the arguments.
Note:
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//MinMax.java
5.
Write a console application which reads 1 character and displays whether it is a letter, a digit, or nonalphanumeric.
The main method MUST call 1 method:
charType, which takes a char argument and returns “letter” if the argument is a letter, “digit” if the
argument is a digit, “non-alphanumeric” if the argument is non-alphanumeric.
Note:
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//CharacterType.java
6.
Write a console application to compute mortgage payments. The following formula is used to calculate
the fixed monthly payment required to fully amortize a loan of L dollars over a term of n months at a
monthly interest rate of c (if the quoted rate is 0.625%, c is 0.00625)
L[c(1 + c)n]/[(1 + c)n - 1]
Note:
You must write an API for each method that you define.
In addition, you must include the following comment at the top of the program
//Your name
//Your email address
//Mortgage.java
© Copyright 2026 Paperzz