This lab discusses and provides examples of both built-in and user-defined functions. In Java function are referred to as methods. Therefore, in the rest of this lab, the term methods will be used to refer to functions. The lab will cover the type of methods, naming of functions, the scope of variables and recursion.
2. Introduction
This lab discusses and provides examples of both built-in and user-defined
functions. In Java function are referred to as methods. Therefore, in the rest of
this lab, the term methods will be used to refer to functions. The lab will cover
the type of methods, naming of functions, the scope of variables and recursion.
Skill-set
By completing this lab, the students will develop the following skills:
• Declare various methods
• Use appropriate modifier/name for the method
• Call methods with the correct parameters
• Accurately manage the scope of the variable
• Implement a simple recursion
How to use this lab?
Follow the lab instruction in step by step and complete all exercises. Watch
the associated videos.
Modify the examples to and exercises to experiment with different scenarios
to solve a similar problem.
Click the QR code to access the videos and PowerPoint icon to access the
associated PowerPoints.
3. What are functions
So far, you have seen the following methods:
Main: The first function that is
executed when you run your Java
program
println: This function
displays/prints results on the
computer screen
nextFloat: Allows the user to
enter a floating point value
So, what is a methods?
A method is one or more line of code that performs a specification process. From
the above examples, you can see that each function has a unique process.
Built-in function
Methods that are already available in the programming language (Java) are called
built-in functions. In Java, methods cannot exist without a class. You may hear
the word functions. Methods and functions are the same. Below are some of the
methods available in the Math class.
Here is how to call one of the Math
function, pow(x,y):
This Math is
a must. It
represent
the class
Math.
Function
name
The first
parameter
The second
parameter
The function pow(x,y) requires two parameters that are x and y. After it performs its
process, it returns a double value.
3
4. 4
String methods
Java has many important built-in String methods that allow you to manipulate
text. Strings are a sequence of characters. In Java programming language, strings
are treated as objects. The Java platform provides the String class to create and
manipulate strings.
This example uses the most commonly used String methods.
• Line 7: The method length() returns the number of char in a string including
white space.
• Lino 8: the method toUpperCase() converts the string to upper case
• Line 9: the method toLowerCase() converts the string to lower case
• Line 10: the method indexOF(String str) returns the index within this string
of the first occurrence of the specified substring
• Line 11: The method substring(int beginIndex) Returns a new string that is a
substring of this string.
• Lines 12-13: The method valueOf() Returns the string representation of the
passed data type argument.
• Line 17: The method trim() returns a copy of the string, with leading and
trailing whitespace omitted.
Refer to this link for more String functions with examples.
5. User Define Functions
In addition to the built-in Java methods, the programmer can create his/her own
methods. These methods are called User Defined Functions.
Why do I need to write a user defined functions?
There are two main reasons for why you need to create your own
functions:
1. Structuring your code (modularity): functions allow you to structure
your long code into separate building blocks which we call functions or
methods. Each function will perform a specific process. Some of the
operations that may need a separate method are:
• A method that allows the user to enter data using a keyboard or
to read data from an external file
• A method that performs a calculation and sends back the results
• A method that set values for the class variables
• A method that gets values of the class variables
• A method that displays the results
These are only examples. There is no limit to how many methods that
you can create.
2. Reusing code: Once a method is created, you will be able to call it multiple
times without the need to recreate it. This feature improves the re-
usability of your code. Of course, if needed you can override a method by
changing its process or overload a method by adding more processes to an
existing method. Override, and overload processes are not the subject of
this course. They will be discussed in details in another course named
Object Oriented Programming.
Rules for selecting a function name
The same rules that are used to name variables are applied to the function
name. Please re-visit Lab 2 - Data Types and Variables.
5
6. Types of methods
There are four types of methods based on parameters that they accept and values
they return.
1. A methods that does not accept
and does not return a value
Function A
The word void means
that the function does
not return a value.
Functions that are in
the main class must
be static.
An empty bracket
means this function
does not accept
parameters.
2. A method that does not accept
parameters, but returns a value
Function B
This function
returns double.
No parameters
Each function that
returns a value must
include the command
return
This is the value that
will be returned by
the function.
6
7. 3. A method that accepts a
parameter and does not return a
value.
Function C
The word void means
that the function does
not return a value.
This function requires
one parameter of
type double
As this function does not return a
value, there is no return command
in the body of the function.
4. A method that accepts a
parameter and returns a value. Function D
This function returns
the average as double.
This function requires
two double
parameters x and y.
Returns Avg to the
caller function.
Calling methods
To call a method, you need the method name and the parameters between
two brackets. The returned value is usually stored in a variable. Let us call
the last function that we created that is calAverage(x,y):
A new variable
to store the
result
Function name
The values of first and
second parameters
separated by a comma (,)
7
8. 8
Declaring a method
In java Language, a method consists of 6 main
components:
1. Modifiers—such as public, private, and others you will learn about
later.
2. The return type—the data type of the value returned by the method,
or void if the method does not return a value.
3. The method name—the rules for variable names apply to method
names as well, but the convention is a little different.
4. The parameter list in parenthesis—a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, ().
If there are no parameters, you must use empty parentheses.
5. The method body, enclosed between braces—the method's code,
including the declaration of local variables, goes here.
6. An exception list—to be discussed in the Object Oriented Programming
course.
1. Modifiers
2. The
return
type
3. The
method
name
4. The
parameters
list
5. The body
of the
method
9. An example
Write a Java program that allows the user to enter the marks of 3
assessment, calculate the total and average. Create at least one function
beside the main functions.
The following code provide the solution without using a user defined
methods.
The above code performs many functions:
Allowing user to enter data: Line 7 to 14 perform this task
Calculating the total: Line 15 calculates the total
Calculating the average: Line 16 calculates the average
Displaying the results: Line 18 to 19 display the results
Each of the above can be created as a method. You can also group methods.
For example entering data and calculating total can be one method.
9
10. Here is the same solution, but divided into two methods that are main and
calTotal.
• The method calTotal starts from line 12 to line 22. Please note this
function is written outside the main method, but inside the class Main.
The class begin at line 3 and ends in line 24.
• The method calTotal does not accept parameters, but returns the
double.
• Line 6 in the main function calls the function calTotal().
10
11. Sequence of execution
1
2
34
5
When you run the code, the first method that is executed is the main
method.1
2
3
4
5
When the execution reach line 6 where the method calTotal is called, the
execution moves to the function calTotal starting from line 12.
The body of the method calTotal is executed from line 13 to 21
When the execution reaches return(total), it goes back to the main method
Then, the rest of the main method is executed start from line 7 to 9.
11
12. 12
Scope of the variables
In Java, there are two types of variable that are:
Local variable: it is accessible only from the block that is declared in. The block can be
a class, method, for loop, if statement, etc. Any code the is put between two brace
brackets is considered a block {. }
Instance Variable: it is declared outside the methods and accessible by all class
methods.
We will discuss the scope of a variable when we get to selections and iterations.
An example on scope of variables
In this example, we will create a basic method to calculate the value of y using the
value of x.
y = x * 20 + 5;
The above code will generate an error because we are declaring y only inside the
method calY line 10. When we try to access y in the main method in line 6, we get an
error.
How to solve this problem?
13. 13
There are different ways to solve this problem. One way is to declare y outside
both methods. Such variable is called the instance variable. It is accessible by
all methods in the class.
See line 3 of the following code.
Please note the keyword static in line 3. variables that you declare in the main
class need to be declared as static.
We have also delete double from line 12. If you keep it in line 12, the result of y
will always be zero, because they in the line 12 will be considered a local
variable for the method calY and the instance variable will stay at zero.
Try to change line 3 to static double y = 30;
and line 12 to double y = x * 20 + 5; and run the code.
Discuss what has happened and why you are getting the result as y: 30.0;
Discussion
14. 14
An example
In this example, we will return to our first example that calculates the total of 3
assessments and display the average. However, we will create four methods and use
the scope of variables. Here are the methods.
Instance variables
accessible by all
methods
The main method
that manages the
execution of the
code
This method allows
user to enter the 3
marks. It does not
calculate total.
This method only
calculates total and
stores it in the instance
variable total
This method only
calculates average and
stores it in the instance
variable avg
All methods that we used in this example do not accept parameters and do not
return values. They depend on the instance variables to store data.
15. 15
Recursion
You have seen that a method can be called from another method. When a method
calls itself, this process is referred to as recursion. See this example.
Line 11 is calling the same method that includes line 12 itself. This is recursion. To
avoid having an infinitive loop, you need a condition that controls when the
method can call itself. Line 10 is the condition. We will discuss all type of
situations in lab 4. For now, you need to know that the method countto10 is called
only when n is less than 10.
In many cases, recursion can be replaced by loops as we will see in lab5. One
drawback of recursion is that it often requires more memory compared to loops.
For more examples on recursion, please visit this link.
16. Exercises:
1. Write a program that would calculate and output the area of a triangle. Assume base and
height are initialized to 10 and 8 in the program.
Hint: area of a triangle is its base multiplied by its height divided by two.
2. Modify question 3 so that the program accepts the base and height in centimeters from the
user. The program then calculates and outputs the area of the triangle.
3. Write a program to convert Fahrenheit to Celsius temperature and output the result on the
screen.
Hint: Celsius = (Fahrenheit – 32) * 5/9
4. Write a program to prompt the user to enter a value for an amount of money in US dollar.
The program should then convert the amount entered to UAE dirham and output the result
on the screen. Assume one US dollar is AED 3.7
5. The over time rate for a company operating in the UAE is 1.5 times the normal rate. Write a
program to ask the operator to enter the normal rate in UAE dirham, the number of hours
worked at normal rate, and the number of hours worked at overtime rate. The program
should then calculate the gross salary and display the result on the screen.
6. Write a program that asks the user to enter the number of DVDs that he wishes to rent and
the charge of renting a DVD, and then calculates the total charge that he should pay.
7. Write a program that will calculate and display the average mark of 3 different tests. The
program should ask the student to enter the 3 marks first and then display the result.
8. Ahmed wishes to buy 3 books from a bookshop that offers 10% discount on books. Write a
program that asks Ahmed to enter the price of each book and then calculates and displays
the amount of money that he should pay.
9. Salem bought a laptop and printer from a shop that offers discounts on some products. The
original prices of the laptop and printer were 3900 AED and 800 AED respectively. Salem
managed to get 15% discount on the laptop and 10% discount on the printer. Write a
program to find out the amount of money that Salem paid for both items.
10. A family of 4 (husband, wife, 3 years old son and 10 months old daughter). They have
decided to visit Egypt during the Eid break. For the children he will pay 60% and 10% of the
normal ticket price for his son and daughter respectively. Write an algorithm that asks the
husband to enter the price of the air ticket and then calculates and displays the amount of
money he should pay for the 4 tickets.
Complete the following exercises by creating at least one method beside the
main method: