SlideShare a Scribd company logo
1Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Chapter 2 Methods
2Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Motivations
A method is a construct for grouping statements together
to perform a function. Using a method, you can write the
code once for performing the function in a program and
reuse it by many other programs. For example, often you
need to find the maximum between two numbers.
Whenever you need this function, you would have to write
the following code:
int result;
if (num1 > num2)
result = num1;
else
result = num2;
If you define this function for finding a
maximum number between any two
numbers in a method, you don’t have to
repeatedly write the same code. You
need to define it just once and reuse it
by any other programs.
3Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Objectives
To define methods, invoke methods, and pass arguments to a
method.
To develop reusable code that is modular, easy-to-read, easy-to-
debug, and easy-to-maintain.
To determine the scope of variables.
4Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
5Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Method Signature
Method signature is the combination of the method name and the
parameter list.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
6Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Formal Parameters
The variables defined in the method header are known as
formal parameters.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
7Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
8Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Return Value Type
A method may return a value. The returnValueType is the data
type of the value the method returns. If the method does not return
a value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
modifier
return value
type
method
name
formal
parameters
return value
method
body
method
header
parameter list
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
method
signature
9Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Calling Methods
Listing 2.1 Testing the max method
This program demonstrates calling a method max
to return the largest of the int values
TestMaxTestMax
10Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Calling Methods, cont.
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
pass the value of i
pass the value of j
animation
11Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
i is now 5
animation
12Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
j is now 2
animation
13Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
invoke max(i, j)
animation
14Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
animation
15Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
declare variable result
animation
16Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
(num1 > num2) is true since
num1 is 5 and num2 is 2
animation
17Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
result is now 5
animation
18Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
return result, which is 5
animation
19Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
return max(i, j) and assign the
return value to k
animation
20Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Trace Method Invocation
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);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Execute the print statement
animation
21Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
CAUTION
A return statement is required for a value-returning method. The
method shown below in (a) is logically correct, but it has a
compilation error because the Java compiler thinks it possible that
this method does not return any value.
To fix this problem, delete if (n < 0) in (a), so that the compiler
will see a return statement to be reached regardless of how the if
statement is evaluated.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
(a)
Should be
(b)
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
22Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the max method
using ClassName.methodName (e.g., TestMax.max).
23Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
void Method Example
This type of method does not return a value. The method
performs some actions.
TestVoidMethodTestVoidMethod
24Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables
A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local
variable must be declared before it can be
used.
25Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different non-
nesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.
26Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
The scope of j
The scope of i
27Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables, cont.
public static void method1() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
}
It is fine to declare i in two
non-nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
sum += i;
}
}
It is wrong to declare i in
two nesting blocks
28Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
}
29Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671
Scope of Local Variables, cont.
// With no errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}

More Related Content

What's hot

Pointers in C
Pointers in CPointers in C
Pointers in C
Kamal Acharya
 
Method overriding
Method overridingMethod overriding
Method overriding
Azaz Maverick
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Functions In C
Functions In CFunctions In C
Functions In C
Simplilearn
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
Praveen M Jigajinni
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
রাকিন রাকিন
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
Rajab Ali
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructorsRavi_Kant_Sahu
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 

What's hot (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Interface in java
Interface in javaInterface in java
Interface in java
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Functions In C
Functions In CFunctions In C
Functions In C
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Java input
Java inputJava input
Java input
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Strings
StringsStrings
Strings
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 

Viewers also liked

Chapter 5 Class File
Chapter 5 Class FileChapter 5 Class File
Chapter 5 Class File
Khirulnizam Abd Rahman
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateTips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada template
Khirulnizam Abd Rahman
 
Topik 3 Masyarakat Malaysia dan ICT
Topik 3   Masyarakat Malaysia dan ICTTopik 3   Masyarakat Malaysia dan ICT
Topik 3 Masyarakat Malaysia dan ICT
Khirulnizam Abd Rahman
 
Chapter 6 Java IO File
Chapter 6 Java IO FileChapter 6 Java IO File
Chapter 6 Java IO File
Khirulnizam Abd Rahman
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
Khirulnizam Abd Rahman
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
Html5 + Bootstrap & Mobirise
Html5 + Bootstrap & MobiriseHtml5 + Bootstrap & Mobirise
Html5 + Bootstrap & Mobirise
Khirulnizam Abd Rahman
 
Mobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaMobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordova
Khirulnizam Abd Rahman
 
Android app development Hybrid approach for beginners
Android app development  Hybrid approach for beginnersAndroid app development  Hybrid approach for beginners
Android app development Hybrid approach for beginners
Khirulnizam Abd Rahman
 
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareTopik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Khirulnizam Abd Rahman
 
Android app development hybrid approach for beginners - Tools Installations ...
Android app development  hybrid approach for beginners - Tools Installations ...Android app development  hybrid approach for beginners - Tools Installations ...
Android app development hybrid approach for beginners - Tools Installations ...
Khirulnizam Abd Rahman
 

Viewers also liked (12)

Chapter 5 Class File
Chapter 5 Class FileChapter 5 Class File
Chapter 5 Class File
 
Tips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada templateTips menyediakan slaid pembentangan berkesan - tiada template
Tips menyediakan slaid pembentangan berkesan - tiada template
 
Topik 3 Masyarakat Malaysia dan ICT
Topik 3   Masyarakat Malaysia dan ICTTopik 3   Masyarakat Malaysia dan ICT
Topik 3 Masyarakat Malaysia dan ICT
 
Chapter 6 Java IO File
Chapter 6 Java IO FileChapter 6 Java IO File
Chapter 6 Java IO File
 
Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
Html5 + Bootstrap & Mobirise
Html5 + Bootstrap & MobiriseHtml5 + Bootstrap & Mobirise
Html5 + Bootstrap & Mobirise
 
Mobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordovaMobile Web App development multiplatform using phonegap-cordova
Mobile Web App development multiplatform using phonegap-cordova
 
Android app development Hybrid approach for beginners
Android app development  Hybrid approach for beginnersAndroid app development  Hybrid approach for beginners
Android app development Hybrid approach for beginners
 
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan HeartwareTopik 4 Teknologi Komputer: Hardware, Software dan Heartware
Topik 4 Teknologi Komputer: Hardware, Software dan Heartware
 
Android app development hybrid approach for beginners - Tools Installations ...
Android app development  hybrid approach for beginners - Tools Installations ...Android app development  hybrid approach for beginners - Tools Installations ...
Android app development hybrid approach for beginners - Tools Installations ...
 

Similar to Chapter 2 Java Methods

06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
RohitNukte
 
Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"
Gouda Mando
 
slide6.pptx
slide6.pptxslide6.pptx
slide6.pptx
ssusere3b1a2
 
4. functions
4. functions4. functions
4. functions
PhD Research Scholar
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
FarhanAhmade
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Presentation1 computer shaan
Presentation1 computer shaanPresentation1 computer shaan
Presentation1 computer shaan
walia Shaan
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Ontico
 
Functions
FunctionsFunctions
Functions
Swarup Boro
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
ADITYA BHARTI
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
Eng Teong Cheah
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Chapter 6 Methods.pptx
Chapter 6 Methods.pptxChapter 6 Methods.pptx
Chapter 6 Methods.pptx
ssusere3b1a2
 

Similar to Chapter 2 Java Methods (20)

06slide.ppt
06slide.ppt06slide.ppt
06slide.ppt
 
Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"
 
05slide
05slide05slide
05slide
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
slide6.pptx
slide6.pptxslide6.pptx
slide6.pptx
 
4. functions
4. functions4. functions
4. functions
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Presentation1 computer shaan
Presentation1 computer shaanPresentation1 computer shaan
Presentation1 computer shaan
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
 
Functions
FunctionsFunctions
Functions
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
Computer java programs
Computer java programsComputer java programs
Computer java programs
 
Xamarin: C# Methods
Xamarin: C# MethodsXamarin: C# Methods
Xamarin: C# Methods
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Chapter 6 Methods.pptx
Chapter 6 Methods.pptxChapter 6 Methods.pptx
Chapter 6 Methods.pptx
 

More from Khirulnizam Abd Rahman

Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Khirulnizam Abd Rahman
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanPanduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Topik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi MaklumatTopik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi Maklumat
Khirulnizam Abd Rahman
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Khirulnizam Abd Rahman
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
Khirulnizam Abd Rahman
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
Khirulnizam Abd Rahman
 
DTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of ProgrammingDTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of Programming
Khirulnizam Abd Rahman
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanNpwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Khirulnizam Abd Rahman
 
Simple skeleton of a review paper
Simple skeleton of a review paperSimple skeleton of a review paper
Simple skeleton of a review paper
Khirulnizam Abd Rahman
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell   khirulnizamRangka kursus pembangunan aplikasi android kuiscell   khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Khirulnizam Abd Rahman
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam Abd Rahman
 
Senarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanSenarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahan
Khirulnizam Abd Rahman
 
Al mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratAl mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratKhirulnizam Abd Rahman
 
Android development beginners faq
Android development  beginners faqAndroid development  beginners faq
Android development beginners faq
Khirulnizam Abd Rahman
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam Abd Rahman
 

More from Khirulnizam Abd Rahman (18)

Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
Topik 2 Sejarah Perkembanggan Ilmu NBWU1072
 
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan InsanPanduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
Panduan tugasan Makmal Teknologi Maklumat dalam Kehidupan Insan
 
Topik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi MaklumatTopik 1 Islam dan Teknologi Maklumat
Topik 1 Islam dan Teknologi Maklumat
 
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
Application of Ontology in Semantic Information Retrieval by Prof Shahrul Azm...
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
DTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of ProgrammingDTCP2023 Fundamentals of Programming
DTCP2023 Fundamentals of Programming
 
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan InsanNpwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
Npwu-mpu 3252 Teknologi Maklumat dalam Kehidupan Insan
 
Simple skeleton of a review paper
Simple skeleton of a review paperSimple skeleton of a review paper
Simple skeleton of a review paper
 
Airs2014 brochure
Airs2014 brochureAirs2014 brochure
Airs2014 brochure
 
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell   khirulnizamRangka kursus pembangunan aplikasi android kuiscell   khirulnizam
Rangka kursus pembangunan aplikasi android kuiscell khirulnizam
 
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copyKhirulnizam   malay proverb detection - mobilecase 19 sept 2012 - copy
Khirulnizam malay proverb detection - mobilecase 19 sept 2012 - copy
 
Maklumat program al quran dan borang
Maklumat program al quran dan borangMaklumat program al quran dan borang
Maklumat program al quran dan borang
 
Senarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahanSenarai doa al-mathurat sughro - dengan terjemahan
Senarai doa al-mathurat sughro - dengan terjemahan
 
Al mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathuratAl mathurat sughra - ringkas - m-mathurat
Al mathurat sughra - ringkas - m-mathurat
 
Kemalangan akibat tumpuan terganggu
Kemalangan akibat tumpuan tergangguKemalangan akibat tumpuan terganggu
Kemalangan akibat tumpuan terganggu
 
Android development beginners faq
Android development  beginners faqAndroid development  beginners faq
Android development beginners faq
 
Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...Khirulnizam - students experience in using blog as a learning tool - world co...
Khirulnizam - students experience in using blog as a learning tool - world co...
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

Chapter 2 Java Methods

  • 1. 1Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Chapter 2 Methods
  • 2. 2Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a program and reuse it by many other programs. For example, often you need to find the maximum between two numbers. Whenever you need this function, you would have to write the following code: int result; if (num1 > num2) result = num1; else result = num2; If you define this function for finding a maximum number between any two numbers in a method, you don’t have to repeatedly write the same code. You need to define it just once and reuse it by any other programs.
  • 3. 3Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Objectives To define methods, invoke methods, and pass arguments to a method. To develop reusable code that is modular, easy-to-read, easy-to- debug, and easy-to-maintain. To determine the scope of variables.
  • 4. 4Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Defining Methods A method is a collection of statements that are grouped together to perform an operation. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 5. 5Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Method Signature Method signature is the combination of the method name and the parameter list. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 6. 6Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Formal Parameters The variables defined in the method header are known as formal parameters. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 7. 7Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 8. 8Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Return Value Type A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void. public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } modifier return value type method name formal parameters return value method body method header parameter list Define a method Invoke a method int z = max(x, y); actual parameters (arguments) method signature
  • 9. 9Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Calling Methods Listing 2.1 Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMaxTestMax
  • 10. 10Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Calling Methods, cont. 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } pass the value of i pass the value of j animation
  • 11. 11Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } i is now 5 animation
  • 12. 12Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } j is now 2 animation
  • 13. 13Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } invoke max(i, j) animation
  • 14. 14Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2 animation
  • 15. 15Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } declare variable result animation
  • 16. 16Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } (num1 > num2) is true since num1 is 5 and num2 is 2 animation
  • 17. 17Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } result is now 5 animation
  • 18. 18Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } return result, which is 5 animation
  • 19. 19Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } return max(i, j) and assign the return value to k animation
  • 20. 20Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Trace Method Invocation 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); } public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } Execute the print statement animation
  • 21. 21Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 CAUTION A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value. To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated. public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } (a) Should be (b) public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else return –1; }
  • 22. 22Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).
  • 23. 23Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 void Method Example This type of method does not return a value. The method performs some actions. TestVoidMethodTestVoidMethod
  • 24. 24Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.
  • 25. 25Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different non- nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.
  • 26. 26Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable. public static void method1() { . . for (int i = 1; i < 10; i++) { . . int j; . . . } } The scope of j The scope of i
  • 27. 27Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables, cont. public static void method1() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { x += i; } for (int i = 1; i < 10; i++) { y += i; } } It is fine to declare i in two non-nesting blocks public static void method2() { int i = 1; int sum = 0; for (int i = 1; i < 10; i++) { sum += i; } } It is wrong to declare i in two nesting blocks
  • 28. 28Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables, cont. // Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; } }
  • 29. 29Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671 Scope of Local Variables, cont. // With no errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } }