SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
CIS 1403
Fundamentals of
Programming
Lab 3: User Defined
Functions/Methods
1
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.
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
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.
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
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
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
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
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
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
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
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
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
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
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.
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:

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Ppt chapter12
Ppt chapter12Ppt chapter12
Ppt chapter12
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
 
Chapter 05
Chapter 05Chapter 05
Chapter 05
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Chapter 04
Chapter 04Chapter 04
Chapter 04
 
Pptchapter04
Pptchapter04Pptchapter04
Pptchapter04
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Ap Power Point Chpt3
Ap Power Point Chpt3Ap Power Point Chpt3
Ap Power Point Chpt3
 
Java method
Java methodJava method
Java method
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Hemajava
HemajavaHemajava
Hemajava
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
17515
1751517515
17515
 
Methods in C#
Methods in C#Methods in C#
Methods in C#
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
11. java methods
11. java methods11. java methods
11. java methods
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
Abap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorialsAbap object-oriented-programming-tutorials
Abap object-oriented-programming-tutorials
 

Ähnlich wie CIS 1403 lab 3 functions and methods in Java

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4dplunkett
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classemecklenburgstrelitzh
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access PrinciplePhilip Schwarz
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
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 presentationbhargavi804095
 
Lecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionLecture4_Method_overloading power point presentaion
Lecture4_Method_overloading power point presentaionbhargavi804095
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdfHome
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesSakkaravarthiS1
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Mohamed Essam
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class featuresRakesh Madugula
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 

Ähnlich wie CIS 1403 lab 3 functions and methods in Java (20)

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classe
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
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
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
OOPSCA1.pptx
OOPSCA1.pptxOOPSCA1.pptx
OOPSCA1.pptx
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
DATA STRUCTURE.pdf
DATA STRUCTURE.pdfDATA STRUCTURE.pdf
DATA STRUCTURE.pdf
 
DATA STRUCTURE
DATA STRUCTUREDATA STRUCTURE
DATA STRUCTURE
 

Kürzlich hochgeladen

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Kürzlich hochgeladen (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

CIS 1403 lab 3 functions and methods in Java

  • 1. CIS 1403 Fundamentals of Programming Lab 3: User Defined Functions/Methods 1
  • 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: