SlideShare a Scribd company logo
Chapter 4: Methods
Asserting Java
©Rick Mercer
Methods
Methods
We have used some existing methods without
fully understanding their implementation
– System.out's print, println
– String's length, charAt, indexOf, toUpperCase
– Scanner's nextDouble, nextInt
– BankAccount's withdraw, deposit
Java has thousands of methods
– We often need to create our own
Methods
 There are two major components to a method
– the method heading with
 access mode, return type, name, parameters
– the block
 a pair of curly braces containing code that fulfills the
method's responsibility
 Method headings specify the number and types of
arguments required to use the method
Method Heading
with documentation
/*
* Return a new string that is a substring of this string.
* The substring begins at the specified beginIndex and
* extends to the character at index endIndex-1.
* Thus the length of the substring is endIndex-beginIndex.
*
* Examples:
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
*
* Parameters:
* beginIndex - the beginning index, inclusive.
* endIndex - the ending index, exclusive.
*
* Returns: the specified substring.
*/
public String substring(int beginIndex, int endIndex)
Using JUnit to demo substring
What method headings tell us
 Method headings provide the information needed to
use it they show us how to send messages
public String substring(int beginIndex, int endIndex)
1 2 3 5 4 5 4
1 Where is the method accessible
2 What does the method evaluate to?
3 What is the method name?
4 What type arguments are required?
5 How many arguments are required?
Arguments are assigned to
parameters
 The substring method requires two arguments in
order to specify the portion of the string to return
 When the message is sent
– the 1st argument 0 is assigned to parameter
beginIndex
– the 2nd argument 6 is assigned to parameter endIndex
fullName.substring(0, 6);
public String substring(int beginIndex, int endIndex)
Implementation of the method is not shown here
Arguments  Parameters
 When a message is sent
– the first argument is assigned to the first parameter,
– second argument gets assigned to the second parameter,...
 If you do not supply the correct number and type of
arguments, you get compiletime errors
fullName.substring("wrong type");
fullName.substring(0, 6, fullName.length());
fullName.substring();
fullName.substring(0.0, 6.0);
BTW: This returns the string form index to the end
fullName.substring(2); // sometimes convenient
Method Heading:
General Form
 General form of a Java method heading
public return-type method-name ( parameter-1,
parameter-2, parameter-n, ...
)
– public says a method is known where objects are constructed
– return-type may be any primitive type, any class, or void
– A void method returns nothing, therefore,
– a void method can not be assigned to anything
– a void method can not be printed with println
Method Headings
 Example method headings think of class as type
public char charAt(int index) // class String
public int indexOf(String sub) // class String
public void withdraw(double amt) // class BankAccount
public String getText() // class Jbutton
public String setText(String str) // class Jbutton
public void setSize(int x, int y) // class JFrame
public int nextInt() // class Scanner
public int nextDouble() // class Scanner
public int next() // class Scanner
public int nextLine() // class Scanner
Parameters
 Parameters, which are optional, specify the number
and type of arguments required in the message
– Sometimes methods need extra information
– How much to deposit?
– substring need to know begin- and end-indexes?
 General form of a parameter between ( and ) in
method headings
class-name identifier
-or-
primitive-type identifier
The Block
 The method body is Java code enclosed within a
block { }
 Curly braces have the same things we've seen in
main methods
– variable declarations and initializations int creditOne = 0;
– objects String str = "local";
– messages boolean less = str.compareTo("m") < 0;
 Method bodies have access to parameters
– Hence, methods are general enough to be reused with many
different arguments
The return statement
 All non-void methods must return a value
– The type of the value is defined in the method heading
 Use Java's return statement
return expression ;
 Example in the context of a method's block
public double f(double x) {
return 2.0 * x - 1.0;
}
Code Demo
 Given the following documented method heading,
– Write a test method in ControlFunTest.java
 The assertions are expected to fail
– Write the actual method in ControlFun.java
/*
* Return largest of 3 integer arguments
* max(1, 2, 3) returns 3
* max(1, 3, 2) returns 3
* max(-1, -2, -3) returns -1
*/
public int max(int a, int b, int c) {
return 0;
}
Methods: A Summary
 Method headings provide this information on usage:
– is the method is available from other places in code?
 public methods are known in the block where constructed
– return-type the kind of value a message evaluates to
– method-name that begins a valid method call
– parameter-list the number and type of needed arguments
– documentation to describe what the method does
 The block is where your algorithm gets implemented
 The parameters are accessible within the block
 Methods usually return a value of the correct type
 Methods must be fully tested (at least in this course)

More Related Content

Similar to Methods.ppt (20)

PPTX
Java method present by showrov ahamed
Md Showrov Ahmed
 
PPTX
Hemajava
SangeethaSasi1
 
PPT
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
DOCX
Methods in Java
Kavitha713564
 
PPTX
Ifi7107 lesson4
Fernando Loizides
 
PPTX
09. Java Methods
Intro C# Book
 
DOCX
The Java Learning Kit Chapter 5 – Methods and Modular.docx
arnoldmeredith47041
 
PPTX
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
PPTX
Chap2 class,objects contd
raksharao
 
PPT
Class & Object - User Defined Method
PRN USM
 
PPTX
Java Basics
Emprovise
 
PPT
Methods intro-1.0
BG Java EE Course
 
PPTX
JAVA LOOP.pptx
SofiaArquero2
 
DOCX
Java execise
Keneth miles
 
PPT
Best Core Java Training In Bangalore
rajkamaltibacademy
 
PPTX
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
PPT
M C6java3
mbruggen
 
PPT
Java
mbruggen
 
PPT
Cso gaddis java_chapter5
mlrbrown
 
Java method present by showrov ahamed
Md Showrov Ahmed
 
Hemajava
SangeethaSasi1
 
Explain Classes and methods in java (ch04).ppt
ayaankim007
 
Methods in Java
Kavitha713564
 
Ifi7107 lesson4
Fernando Loizides
 
09. Java Methods
Intro C# Book
 
The Java Learning Kit Chapter 5 – Methods and Modular.docx
arnoldmeredith47041
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Chap2 class,objects contd
raksharao
 
Class & Object - User Defined Method
PRN USM
 
Java Basics
Emprovise
 
Methods intro-1.0
BG Java EE Course
 
JAVA LOOP.pptx
SofiaArquero2
 
Java execise
Keneth miles
 
Best Core Java Training In Bangalore
rajkamaltibacademy
 
Java As an OOP Language,Exception Handling & Applets
Helen SagayaRaj
 
M C6java3
mbruggen
 
Java
mbruggen
 
Cso gaddis java_chapter5
mlrbrown
 

Recently uploaded (20)

PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
PPTX
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
PDF
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
PPT
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PDF
John Keats introduction and list of his important works
vatsalacpr
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
Virus sequence retrieval from NCBI database
yamunaK13
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
John Keats introduction and list of his important works
vatsalacpr
 
Ad

Methods.ppt

  • 1. Chapter 4: Methods Asserting Java ©Rick Mercer Methods
  • 2. Methods We have used some existing methods without fully understanding their implementation – System.out's print, println – String's length, charAt, indexOf, toUpperCase – Scanner's nextDouble, nextInt – BankAccount's withdraw, deposit Java has thousands of methods – We often need to create our own
  • 3. Methods  There are two major components to a method – the method heading with  access mode, return type, name, parameters – the block  a pair of curly braces containing code that fulfills the method's responsibility  Method headings specify the number and types of arguments required to use the method
  • 4. Method Heading with documentation /* * Return a new string that is a substring of this string. * The substring begins at the specified beginIndex and * extends to the character at index endIndex-1. * Thus the length of the substring is endIndex-beginIndex. * * Examples: * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * * Parameters: * beginIndex - the beginning index, inclusive. * endIndex - the ending index, exclusive. * * Returns: the specified substring. */ public String substring(int beginIndex, int endIndex)
  • 5. Using JUnit to demo substring
  • 6. What method headings tell us  Method headings provide the information needed to use it they show us how to send messages public String substring(int beginIndex, int endIndex) 1 2 3 5 4 5 4 1 Where is the method accessible 2 What does the method evaluate to? 3 What is the method name? 4 What type arguments are required? 5 How many arguments are required?
  • 7. Arguments are assigned to parameters  The substring method requires two arguments in order to specify the portion of the string to return  When the message is sent – the 1st argument 0 is assigned to parameter beginIndex – the 2nd argument 6 is assigned to parameter endIndex fullName.substring(0, 6); public String substring(int beginIndex, int endIndex) Implementation of the method is not shown here
  • 8. Arguments  Parameters  When a message is sent – the first argument is assigned to the first parameter, – second argument gets assigned to the second parameter,...  If you do not supply the correct number and type of arguments, you get compiletime errors fullName.substring("wrong type"); fullName.substring(0, 6, fullName.length()); fullName.substring(); fullName.substring(0.0, 6.0); BTW: This returns the string form index to the end fullName.substring(2); // sometimes convenient
  • 9. Method Heading: General Form  General form of a Java method heading public return-type method-name ( parameter-1, parameter-2, parameter-n, ... ) – public says a method is known where objects are constructed – return-type may be any primitive type, any class, or void – A void method returns nothing, therefore, – a void method can not be assigned to anything – a void method can not be printed with println
  • 10. Method Headings  Example method headings think of class as type public char charAt(int index) // class String public int indexOf(String sub) // class String public void withdraw(double amt) // class BankAccount public String getText() // class Jbutton public String setText(String str) // class Jbutton public void setSize(int x, int y) // class JFrame public int nextInt() // class Scanner public int nextDouble() // class Scanner public int next() // class Scanner public int nextLine() // class Scanner
  • 11. Parameters  Parameters, which are optional, specify the number and type of arguments required in the message – Sometimes methods need extra information – How much to deposit? – substring need to know begin- and end-indexes?  General form of a parameter between ( and ) in method headings class-name identifier -or- primitive-type identifier
  • 12. The Block  The method body is Java code enclosed within a block { }  Curly braces have the same things we've seen in main methods – variable declarations and initializations int creditOne = 0; – objects String str = "local"; – messages boolean less = str.compareTo("m") < 0;  Method bodies have access to parameters – Hence, methods are general enough to be reused with many different arguments
  • 13. The return statement  All non-void methods must return a value – The type of the value is defined in the method heading  Use Java's return statement return expression ;  Example in the context of a method's block public double f(double x) { return 2.0 * x - 1.0; }
  • 14. Code Demo  Given the following documented method heading, – Write a test method in ControlFunTest.java  The assertions are expected to fail – Write the actual method in ControlFun.java /* * Return largest of 3 integer arguments * max(1, 2, 3) returns 3 * max(1, 3, 2) returns 3 * max(-1, -2, -3) returns -1 */ public int max(int a, int b, int c) { return 0; }
  • 15. Methods: A Summary  Method headings provide this information on usage: – is the method is available from other places in code?  public methods are known in the block where constructed – return-type the kind of value a message evaluates to – method-name that begins a valid method call – parameter-list the number and type of needed arguments – documentation to describe what the method does  The block is where your algorithm gets implemented  The parameters are accessible within the block  Methods usually return a value of the correct type  Methods must be fully tested (at least in this course)