SlideShare uma empresa Scribd logo
1 de 29
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;
}
}

Mais conteúdo relacionado

Mais procurados (20)

String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Type conversion
Type conversionType conversion
Type conversion
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
introduction to python
 introduction to python introduction to python
introduction to python
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
String in java
String in javaString in java
String in java
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 

Destaque

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 templateKhirulnizam 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-cordovaKhirulnizam 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 beginnersKhirulnizam 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 HeartwareKhirulnizam 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
 

Destaque (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 ...
 

Semelhante a Chapter 2 Java Methods

Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Java™ (OOP) - Chapter 5: "Methods"
Java™ (OOP) - Chapter 5: "Methods"Gouda Mando
 
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 2015Codemotion
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Presentation1 computer shaan
Presentation1 computer shaanPresentation1 computer shaan
Presentation1 computer shaanwalia Shaan
 
Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Kotlin Perfomance on Android / Александр Смирнов (Splyt)
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
 
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 programsADITYA BHARTI
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Chapter 6 Methods.pptx
Chapter 6 Methods.pptxChapter 6 Methods.pptx
Chapter 6 Methods.pptxssusere3b1a2
 

Semelhante a 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
 

Mais de 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 NBWU1072Khirulnizam 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 InsanKhirulnizam 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
 
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 InsanKhirulnizam 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 khirulnizamKhirulnizam 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 terjemahanKhirulnizam 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
 
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
 

Mais de 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...
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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; } }