SlideShare a Scribd company logo
1 of 63
Introduction to Java Programming and
Data Structures
Twelfth Edition
Chapter 6
Methods
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Opening Problem
Find the sum of integers from 1 to 10, from 20 to 30, and
from 35 to 45, respectively.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Problem (1 of 2)
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);
sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);
sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Problem (2 of 2)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Solution
MethodDemo
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Defining Methods (1 of 2)
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;
}
Define a method Invoke a method
int z = max(x, y);
actual parameters
(arguments)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Defining Methods (2 of 2)
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
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Method Signature
Method signature is the combination of the method name
and the parameter list.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Actual Parameters
When a method is invoked, you pass a value to the parameter.
This value is referred to as actual parameter or argument.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
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.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Calling Methods (1 of 2)
Testing the max method
This program demonstrates calling a method max to return
the largest of the int values
TestMax
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Calling Methods (2 of 2)
pass the value of i
pass the value of j
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (1 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (2 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (3 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (4 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (5 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (6 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (7 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (8 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (9 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Method Invocation (10 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
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.
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;
}
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.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
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).
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Call Stacks
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (1 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (2 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (3 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (4 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (5 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (6 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (7 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (8 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (9 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Trace Call Stack (10 of 10)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
void Method Example
This type of method does not return a value. The method
performs some actions.
TestVoidMethod
TestReturnGradeMethod
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
TestVoidMethod
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Can you invoke the method using
nPrintln(15, “Computer Science”);
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Pass by Value (1 of 3)
This program demonstrates passing values to the methods.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Pass by Value (2 of 3)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Pass by Value (3 of 3)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Modularizing Code
Methods can be used to reduce redundant coding and
enable code reuse. Methods can also be used to
modularize code and improve the quality of the program.
PrimeNumberMethod
• Modular programming (also referred to as modular
architecture) is a general programming concept. It
involves separating a program’s functions into
independent pieces or building blocks, each containing all
the parts needed to execute a single aspect of the
functionality. Together, the modules make up the
executable application program.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Case Study: Converting Hexadecimals to
Decimals
Write a method that converts a hexadecimal number into a
decimal number.
 
 
 
 
ABCD
A *16 ^3 B *16 ^ 2 C *16 ^1 D *16 ^0
A *16 B *16 C *16 D
10 *16 11 *16 12 *16 13 ?

  
   
    
Hex2Dec
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Overloading Methods
Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
TestMethodOverloading
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Overloading Methods
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (1 of 2)
Sometimes there may be two or more possible matches for
an invocation of a method, but the compiler cannot
determine the most specific match. This is referred to as
ambiguous invocation. Ambiguous invocation is a
compile error.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Ambiguous Invocation (2 of 2)
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (1 of 6)
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.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (2 of 6)
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.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (3 of 6)
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
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (4 of 6)
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
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (5 of 6)
// 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;
}
}
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Scope of Local Variables (6 of 6)
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Method Abstraction
You can think of the method body as a black box that
contains the detailed implementation for the method.
Method Header
Method body
Black Box
Optional arguments
for Input
Optional return
value
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation from the
user.
• Reduce complexity.
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (1 of 4)
Computer programs process numerical data and
characters. You have seen many examples that involve
numerical data. It is also important to understand
characters and how to process them.
As introduced in Section 4.3, each character has a unique
Unicode between 0 and FFFF in hexadecimal (65535 in
decimal). To generate a random character is to generate a
random integer between 0 and 65535 using the following
expression: (note that since 0 <= Math.random() < 1.0, you
have to add 1 to 65535.)
(int)(Math.random() * (65535 + 1))
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (2 of 4)
Now let us consider how to generate a random lowercase
letter. The Unicode for lowercase letters are consecutive
integers starting from the Unicode for 'a', then for 'b', 'c', ...,
and 'z'. The Unicode for 'a' is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (3 of 4)
As discussed in Chapter 2, all numeric operators can be
applied to the char operands. The char operand is cast into
a number if the other operand is a number or a character.
So, the preceding expression can be simplified as follows:
'a' + Math.random() * ('z' - 'a' + 1)
So a random lowercase letter is
(char)('a' + Math.random() * ('z' - 'a' + 1))
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
Case Study: Generating Random
Characters (4 of 4)
To generalize the foregoing discussion, a random
character between any two characters ch1 and ch2 with
ch1 < ch2 can be generated as follows:
(char)(ch1 + Math.random() * (ch2 – ch1 + 1))
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
The RandomCharacter Class (1 of 2)
// RandomCharacter.java: Generate random
characters
public class RandomCharacter {
/** Generate a random character between ch1
and ch2 */
public static char getRandomCharacter(char
ch1, char ch2) {
return (char)(ch1 + Math.random() *
(ch2 - ch1 + 1));
}
/** Generate a random lowercase letter */
public static char
getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}
/** Generate a random uppercase letter */
public static char
getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
RandomCharacter
TestRandomCharacter
Copyright © 2020 Pearson Education, Inc. All Rights Reserved
The RandomCharacter Class (2 of 2)
/** Generate a random digit character */
public static char
getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}
/** Generate a random character */
public static char getRandomCharacter() {
return getRandomCharacter('u0000',
'uFFFF');
}
}
RandomCharacter
TestRandomCharacter

More Related Content

Similar to Chapter 6 Methods.pptx

AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...acijjournal
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And ExpressionPRN USM
 
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxChapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxssusere3b1a2
 
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
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxAnkitaVerma776806
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfjanakim15
 
22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdfPradipShinde53
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java Haim Michael
 
Sample prac exam2013
Sample prac exam2013Sample prac exam2013
Sample prac exam2013hccit
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk Ganesh Samarthyam
 

Similar to Chapter 6 Methods.pptx (20)

Chapter 2 Method in Java OOP
Chapter 2   Method in Java OOPChapter 2   Method in Java OOP
Chapter 2 Method in Java OOP
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
03slide.ppt
03slide.ppt03slide.ppt
03slide.ppt
 
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptxChapter 4 Mathematical Functions, Characters, and Strings.pptx
Chapter 4 Mathematical Functions, Characters, and Strings.pptx
 
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...
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Unit 2
Unit 2Unit 2
Unit 2
 
IT 405
IT 405IT 405
IT 405
 
Module 1 - Python.pdf
Module 1 - Python.pdfModule 1 - Python.pdf
Module 1 - Python.pdf
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
 
22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf22316-2019-Summer-model-answer-paper.pdf
22316-2019-Summer-model-answer-paper.pdf
 
Functional programming in Java
Functional programming in Java  Functional programming in Java
Functional programming in Java
 
APSEC2020 Keynote
APSEC2020 KeynoteAPSEC2020 Keynote
APSEC2020 Keynote
 
Good code
Good codeGood code
Good code
 
Sample prac exam2013
Sample prac exam2013Sample prac exam2013
Sample prac exam2013
 
Clean Code
Clean CodeClean Code
Clean Code
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 

More from ssusere3b1a2

13-Doubly Linked List data structure.pdf
13-Doubly Linked List data structure.pdf13-Doubly Linked List data structure.pdf
13-Doubly Linked List data structure.pdfssusere3b1a2
 
Hashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.pptHashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.pptssusere3b1a2
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptssusere3b1a2
 
stack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptstack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptssusere3b1a2
 
information retrieval project
information retrieval projectinformation retrieval project
information retrieval projectssusere3b1a2
 
information retrieval --> dictionary.ppt
information retrieval --> dictionary.pptinformation retrieval --> dictionary.ppt
information retrieval --> dictionary.pptssusere3b1a2
 
introduction into IR
introduction into IRintroduction into IR
introduction into IRssusere3b1a2
 

More from ssusere3b1a2 (7)

13-Doubly Linked List data structure.pdf
13-Doubly Linked List data structure.pdf13-Doubly Linked List data structure.pdf
13-Doubly Linked List data structure.pdf
 
Hashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.pptHashing data structure in genaral ss.ppt
Hashing data structure in genaral ss.ppt
 
stack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.pptstack in java ds - muhammed sdasdasdasdasdas.ppt
stack in java ds - muhammed sdasdasdasdasdas.ppt
 
stack in java data structure - muhammed .ppt
stack in java data structure - muhammed .pptstack in java data structure - muhammed .ppt
stack in java data structure - muhammed .ppt
 
information retrieval project
information retrieval projectinformation retrieval project
information retrieval project
 
information retrieval --> dictionary.ppt
information retrieval --> dictionary.pptinformation retrieval --> dictionary.ppt
information retrieval --> dictionary.ppt
 
introduction into IR
introduction into IRintroduction into IR
introduction into IR
 

Recently uploaded

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 

Recently uploaded (20)

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 

Chapter 6 Methods.pptx

  • 1. Introduction to Java Programming and Data Structures Twelfth Edition Chapter 6 Methods Copyright © 2020 Pearson Education, Inc. All Rights Reserved
  • 2. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
  • 3. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Problem (1 of 2) int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);
  • 4. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Problem (2 of 2)
  • 5. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Solution MethodDemo
  • 6. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Defining Methods (1 of 2) 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; } Define a method Invoke a method int z = max(x, y); actual parameters (arguments)
  • 7. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Defining Methods (2 of 2) 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
  • 8. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Method Signature Method signature is the combination of the method name and the parameter list.
  • 9. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Formal Parameters The variables defined in the method header are known as formal parameters.
  • 10. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
  • 11. Copyright © 2020 Pearson Education, Inc. All Rights Reserved 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.
  • 12. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Calling Methods (1 of 2) Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMax
  • 13. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Calling Methods (2 of 2) pass the value of i pass the value of j
  • 14. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (1 of 10)
  • 15. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (2 of 10)
  • 16. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (3 of 10)
  • 17. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (4 of 10)
  • 18. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (5 of 10)
  • 19. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (6 of 10)
  • 20. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (7 of 10)
  • 21. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (8 of 10)
  • 22. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (9 of 10)
  • 23. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Method Invocation (10 of 10)
  • 24. Copyright © 2020 Pearson Education, Inc. All Rights Reserved 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. 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; } 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.
  • 25. Copyright © 2020 Pearson Education, Inc. All Rights Reserved 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).
  • 26. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Call Stacks
  • 27. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (1 of 10)
  • 28. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (2 of 10)
  • 29. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (3 of 10)
  • 30. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (4 of 10)
  • 31. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (5 of 10)
  • 32. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (6 of 10)
  • 33. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (7 of 10)
  • 34. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (8 of 10)
  • 35. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (9 of 10)
  • 36. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Trace Call Stack (10 of 10)
  • 37. Copyright © 2020 Pearson Education, Inc. All Rights Reserved void Method Example This type of method does not return a value. The method performs some actions. TestVoidMethod TestReturnGradeMethod
  • 38. Copyright © 2020 Pearson Education, Inc. All Rights Reserved TestVoidMethod
  • 39. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using nPrintln(“Computer Science”, 15); What is the output? Can you invoke the method using nPrintln(15, “Computer Science”);
  • 40. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Pass by Value (1 of 3) This program demonstrates passing values to the methods.
  • 41. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Pass by Value (2 of 3)
  • 42. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Pass by Value (3 of 3)
  • 43. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Modularizing Code Methods can be used to reduce redundant coding and enable code reuse. Methods can also be used to modularize code and improve the quality of the program. PrimeNumberMethod • Modular programming (also referred to as modular architecture) is a general programming concept. It involves separating a program’s functions into independent pieces or building blocks, each containing all the parts needed to execute a single aspect of the functionality. Together, the modules make up the executable application program.
  • 44. Copyright © 2020 Pearson Education, Inc. All Rights Reserved
  • 45. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Case Study: Converting Hexadecimals to Decimals Write a method that converts a hexadecimal number into a decimal number.         ABCD A *16 ^3 B *16 ^ 2 C *16 ^1 D *16 ^0 A *16 B *16 C *16 D 10 *16 11 *16 12 *16 13 ?              Hex2Dec
  • 46. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Overloading Methods Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } TestMethodOverloading
  • 47. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Overloading Methods
  • 48. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Ambiguous Invocation (1 of 2) Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compile error.
  • 49. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Ambiguous Invocation (2 of 2) public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } }
  • 50. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (1 of 6) 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.
  • 51. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (2 of 6) 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.
  • 52. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (3 of 6) 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
  • 53. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (4 of 6) 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
  • 54. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (5 of 6) // 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; } }
  • 55. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Scope of Local Variables (6 of 6) // With errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } }
  • 56. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Method Header Method body Black Box Optional arguments for Input Optional return value
  • 57. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.
  • 58. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (1 of 4) Computer programs process numerical data and characters. You have seen many examples that involve numerical data. It is also important to understand characters and how to process them. As introduced in Section 4.3, each character has a unique Unicode between 0 and FFFF in hexadecimal (65535 in decimal). To generate a random character is to generate a random integer between 0 and 65535 using the following expression: (note that since 0 <= Math.random() < 1.0, you have to add 1 to 65535.) (int)(Math.random() * (65535 + 1))
  • 59. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (2 of 4) Now let us consider how to generate a random lowercase letter. The Unicode for lowercase letters are consecutive integers starting from the Unicode for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a' is (int)'a' So, a random integer between (int)'a' and (int)'z' is (int)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)
  • 60. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (3 of 4) As discussed in Chapter 2, all numeric operators can be applied to the char operands. The char operand is cast into a number if the other operand is a number or a character. So, the preceding expression can be simplified as follows: 'a' + Math.random() * ('z' - 'a' + 1) So a random lowercase letter is (char)('a' + Math.random() * ('z' - 'a' + 1))
  • 61. Copyright © 2020 Pearson Education, Inc. All Rights Reserved Case Study: Generating Random Characters (4 of 4) To generalize the foregoing discussion, a random character between any two characters ch1 and ch2 with ch1 < ch2 can be generated as follows: (char)(ch1 + Math.random() * (ch2 – ch1 + 1))
  • 62. Copyright © 2020 Pearson Education, Inc. All Rights Reserved The RandomCharacter Class (1 of 2) // RandomCharacter.java: Generate random characters public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); } /** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z'); } /** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z'); } RandomCharacter TestRandomCharacter
  • 63. Copyright © 2020 Pearson Education, Inc. All Rights Reserved The RandomCharacter Class (2 of 2) /** Generate a random digit character */ public static char getRandomDigitCharacter() { return getRandomCharacter('0', '9'); } /** Generate a random character */ public static char getRandomCharacter() { return getRandomCharacter('u0000', 'uFFFF'); } } RandomCharacter TestRandomCharacter

Editor's Notes

  1. If this PowerPoint presentation contains mathematical equations, you may need to check that your computer has the following installed: 1) MathType Plugin 2) Math Player (free versions available) 3) NVDA Reader (free versions available) Slides in this presentation contain hyperlinks. JAWS users should be able to get a list of links by using INSERT+F7
  2. for left parenthesis int i = 1 semi colon, i is less than or equal to 10 semi colon i ++ right parenthesis sum + = i semi colon system.out.prinln left parenthesis start double quotation marks Sum from 1 to 10 is end double quotation marks + sum right parenthesis semi colon sum = 0 semi colon for left parenthesis int i = 20 semi colon, i is less than or equal to 30 semi colon i ++ right parenthesis sum + = i semi colon system.out.prinln left parenthesis start double quotation marks Sum from 20 to 30 is end double quotation marks + sum right parenthesis semi colon sum = 0 semi colon for left parenthesis int i = 35 semi colon, i is less than or equal to 45 semi colon i ++ right parenthesis sum + = i semi colon system.out.prinln left parenthesis start double quotation marks Sum from 35 to 45 is end double quotation marks + sum right parenthesis semi colon
  3. int sum = 0 semi colon for left parenthesis int i = i1 semi colon i is less than or equal to i2 semi colon i ++ right parenthesis sum + = i semi colon return sum semi colon right brace public static void main left parenthesis string left bracket right bracket args right parenthesis left brace system.out.println left parenthesis start double quotation marks Sum from 1 to 10 is end double quotation marks + sum left parenthesis 1, 10 right parenthesis, right parenthesis semi colon (sum left parenthesis 1, 10 right parenthesis is highlighted) system.out.println left parenthesis start double quotation marks Sum from 20 to 30 is end double quotation marks + sum left parenthesis 20, 30 right parenthesis, right parenthesis semi colon (sum left parenthesis 20, 30 right parenthesis is highlighted) system.out.println left parenthesis start double quotation marks Sum from 35 to 45 is end double quotation marks + sum left parenthesis 35, 45 right parenthesis, right parenthesis semi colon (sum left parenthesis 35, 45 right parenthesis is highlighted) right brace MethodDemo: https://liveexample.pearsoncmg.com/html/MethodDemo.html
  4. Define a method public static int max open parenthesis int num 1, int num 2 close parenthesis open braces int result Semicolon if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 Semicolon return result Semicolon close braces Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters, arguments
  5. Define a method. Public static int max open parenthesis num 1, int num 2 close parenthesis open braces int results Semicolon This line is labeled, method header. Public static are labeled, modifier. int is labeled return value type. max is labeled method name. num 1 and num 2 are labeled formal parameters. information within the parenthesis is labeled parameter list. max open parenthesis int num 1, int num 2 close parenthesis is labeled, method signature. Below is the method body. if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 return result Semicolon It is labeled return value. Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters (arguments).
  6. Define a method. Public static int max open parenthesis num 1, int num 2 close parenthesis open braces int results Semicolon This line is labeled, method header. Public static are labeled, modifier. int is labeled return value type. max is labeled method name. num 1 and num 2 are labeled formal parameters. information within the parenthesis is labeled parameter list. max open parenthesis int num 1, int num 2 close parenthesis is labeled, method signature. Below is the method body. if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 return result Semicolon It is labeled return value. Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters, arguments.
  7. Define a method. Public static int max open parenthesis num 1, int num 2 close parenthesis open braces int results Semicolon This line is labeled, method header. Public static are labeled, modifier. int is labeled return value type. max is labeled method name. num 1 and num 2 are labeled formal parameters. information within the parenthesis is labeled parameter list. max open parenthesis int num 1, int num 2 close parenthesis is labeled, method signature. Below is the method body. if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 return result Semicolon It is labeled return value. Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters, arguments.
  8. Define a method. Public static int max open parenthesis num 1, int num 2 close parenthesis open braces int results Semicolon This line is labeled, method header. Public static are labeled, modifier. int is labeled return value type. max is labeled method name. num 1 and num 2 are labeled formal parameters. information within the parenthesis is labeled parameter list. max open parenthesis int num 1, int num 2 close parenthesis is labeled, method signature. Below is the method body. if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 return result Semicolon It is labeled return value. Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters (arguments).
  9. Define a method. Public static int max open parenthesis num 1, int num 2 close parenthesis open braces int results Semicolon This line is labeled, method header. Public static are labeled, modifier. int is labeled return value type. max is labeled method name. num 1 and num 2 are labeled formal parameters. information within the parenthesis is labeled parameter list. max open parenthesis int num 1, int num 2 close parenthesis is labeled, method signature. Below is the method body. if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 return result Semicolon It is labeled return value. Invoke a method. int z = max open parenthesis x, y close parenthesis Semicolon x and y are labeled as actual parameters, arguments.
  10. TestMax: https://liveexample.pearsoncmg.com/html/TestMax.html
  11. Public static void main open parenthesis String open bracket close bracket args close parenthesis open braces int i = 5 Semicolon int j = 2 Semicolon int k = max open parenthesis I, j close parenthesis Semicolon System.out.printIn open parenthesis open double quotes The maximum between close double quotes + i + open double quotes and close double quotes + j + open double quotes is close double quotes + k close parenthesis Semicolon public static int max open parenthesis int num 1, int num 2 close parenthesis open braces int result Semicolon if open parenthesis num 1 greater than num 2 close parenthesis result = num 1 Semicolon else result = num 2 Semicolon return result Semicolon The i and j are written as num 1 and num 2 respectively. public static int max is written in both the images. Semicolon after max open parenthesis i, j close parenthesis is written as close braces in the second image.
  12. invoke max open parenthesis i, j close parenthesis, Pass the value of i to num 1, Pass the value of j to num 2, points to the text box, int max open parenthesis num 1, num 2 close parenthesis. The text box with int k = max open parenthesis i, j close parenthesis, and the text box int max open parenthesis num 1, num 2 close parenthesis.
  13. open parenthesis num 1 greater than num 2 close parenthesis is true since num 1 is 5 and num 2 is 2, points to the text if open parenthesis num 1 greater than num 2 close parenthesis. The arrow is also connected to the text, int k = max open parenthesis i, j close parenthesis.
  14. Execute the print statement, points to the text, System.out.printIn open parenthesis open double quotes The maximum between close double quotes + i + open double quotes and close double quotes + j + open double quotes is close double quotes + k close parenthesis.
  15. A. The main method is invoked. The stack has activation record for the main method, with the code k: blank, j: 2, and i: 5. B. The max method is invoked. The stack is divided into two parts. The upper part shows Activation record for the max method, with result: blank, num 2: 2, and num 1: 5. The lower part shows Activation record for the main method, with k: blank, j: 2, and i: 5. An arrow points from j: 2 to num 2: 2. Another arrow points from i: 5 points to num 1: 5. C. The max method is being executed. The stack is divided into two parts. The upper part shows Activation record for the max method, with result: 5, num 2: 2, and num 1: 5. The lower part shows Activation record for the main method, with k: blank, j: 2, and i: 5. d. The max method is finished and the return value is sent to k. The stack reads, Activation record for the main method, with k: 5, j: 2, and i: 5. An arrow from stack C's result: 5 points to k: 5 in stack D. E. The main method is finished. The stack is empty.
  16. Invoke max open parenthesis i, j close parenthesis, points to the text, int k = max open parenthesis i, j close parenthesis. The text, max open parenthesis i, j close parenthesis is connected to public static int max open parenthesis int num 1, int num 2 close parenthesis.
  17. pass the values of i and j to num 1 and num 2, points to the text, max open parenthesis int num 1, int num 2 close parenthesis. This text is also connected to the call stack, that is divided into two parts. The upper part shows num 2: 2, and num 1: 1. The lower part shows Space required for the main method k: blank, j: 2, i: 5. An arrow points from j: 2 to num 2: 2. Another arrow points from i: 5 to num 1: 5.
  18. Declare result, points to the text, int result. The text is also connected to the upper part of the call stack that depicts result: blank, num 2: 2, an num 1: 5. the lower part of the stack reads, Space required for the main method. K: blank. j: 2. i: 5. An arrow points from j: 2 in the lower part of call stack to num 2: 2 in its upper part. Another arrow points from i: 5 in the lower part of call stack to num 1: 5 in its upper part.
  19. open parenthesis num 1 greater than num 2 close parenthesis is true, points to the text, if open parenthesis num 1 greater than num 2 close parenthesis. An arrow points from j: 2 in the lower part of call stack to num 2: 2 in its upper part. Another arrow points from i: 5 in the lower part of call stack to num 1: 5 in its upper part.
  20. Assign num 1 to result, points to the text, result = num 1. The text is connected to result: 5 in the upper part of call stack. An arrow points from j: 2 in the lower part of call stack to num 2: 2 in its upper part. Another arrow points from i: 5 in the lower part of call stack to num 1: 5 in its upper part.
  21. Return result and assign it to k, points to the text, return result. The text is connected to int k = max open parenthesis i, j close parenthesis and also with k: 5 in the lower part of call stack. An arrow points from j: 2 in the lower part of the call stack to num 2: 2 in its upper part. Another arrow points from i: 5 in the lower part of the stack to num 1: 5 in its upper part. An arrow points from result: 5 in the upper part of the call stack to k: 5 in its lower part.
  22. Execute print statement, points to the text, System.out.printIn open parenthesis open double quotes The maximum between close double quotes + i + open double quotes and close double quotes + j + open double quotes is close double quotes + k close parenthesis.
  23. TestVoidMethod: https://liveexample.pearsoncmg.com/html/TestVoidMethod.html TestReturnGradeMethod: https://liveexample.pearsoncmg.com/html/TestReturnGradeMethod.html
  24. Increment: https://liveexample.pearsoncmg.com/html/Increment.html
  25. TestPassByValue: https://liveexample.pearsoncmg.com/html/TestPassByValue.html
  26. The main method is invoked. The stack has activation record for the main method, with the code num 2: 2, and num 1: 1. The swap method is invoked. The stack is divided into two parts. The upper part shows Activation record for the swap method, with temp: blank, n 2: 1, and n 1: 2. The lower part shows Activation record for the main method, with num 2: 2, and num 1: 1. An arrow points from num 2: 2 to n 2: 2. This arrow is labeled as The values of num 1 and num 2 are passed to n 1 and n 2. Another arrow points from num 1: 1 points to n 1: 1. The swap method is executed. The stack is divided into two parts. The upper part shows Activation record for the swap method, with temp: 1, n 2: 1, and n 1: 2. The values for n 1 and n 2 are swapped, but it does not affect num 1 and num 2. The lower part shows Activation record for the main method, with num 2: 2, and num 1: 5. The swap method is finished. The stack reads, Activation record for the main method, with num 2: 2, num 1: 1, and i: 5. The main method is finished. The stack is empty.
  27. GreatestCommonDivisorMethod: https://liveexample.pearsoncmg.com/html/GreatestCommonDivisorMethod.html PrimeNumberMethod: https://liveexample.pearsoncmg.com/html/PrimeNumberMethod.html
  28. A times 16 to the third power + B times 16 to the second power + C times 16 to the first power + D times 16 to the 0 power = left parenthesis, left parenthesis A times 16 + B right parenthesis times 16 + C right parenthesis times 16 + D = left parenthesis, left parenthesis 10 times 16 + 11 right parenthesis times 16 + 12 right parenthesis times 16 + 13 = question mark Hex2Dec: https://liveexample.pearsoncmg.com/html/Hex2Dec.html
  29. TestMethodOverloading: https://liveexample.pearsoncmg.com/html/TestMethodOverloading.html
  30. public static void method 1 open parenthesis close parenthesis open braces, vertical ellipsis. For open parenthesis int i = 1 Semicolon i less than 10 Semicolon i plus plus close parenthesis open braces, vertical ellipsis. Int j, vertical ellipsis. open braces open braces. from int j to open braces, it is under bracket, labeled as The scope of j. From for open parenthesis int i = 1 to open braces, it is under bracket, labeled as, The scope of i.
  31. public static void method open parenthesis close parenthesis open braces int x = 1 Semicolon int y = 1 Semicolon for open parenthesis int i = 1 Semicolon I less than 10 Semicolon I plus plus close parenthesis open braces x + = i Semicolon close braces for open parenthesis int i = 1 Semicolon I less than 10 Semicolon I plus plus close parenthesis y + = i Semicolon An arrow labeled, It is fine to declare i in two non-nesting blocks, point to the close braces after x + = i, and y + = i. public static void method 2 open parenthesis close parenthesis open braces int i = 1 Semicolon int sum = 0 Semicolon for open parenthesis int i = 1 Semicolon i less than 10 Semicolon i plus plus close parenthesis sum + = i Semicolon close braces close braces. Two arrows labeled, It is wrong to declare i in two nesting blocks, point to the region of for open parenthesis int i = 1 Semicolon i less than 10 Semicolon i plus plus close parenthesis sum + = i Semicolon close braces, and the region of int i = 1 till the last close brace.
  32. A downward arrow labeled Optional arguments for input, points to Method header. An upward arrow moves up from Method header. This arrow is labeled as Optional return value.
  33. RandomCharacter: https://liveexample.pearsoncmg.com/html/RandomCharacter.html TestRandomCharacter: https://liveexample.pearsoncmg.com/html/TestRandomCharacter.html
  34. RandomCharacter: https://liveexample.pearsoncmg.com/html/RandomCharacter.html TestRandomCharacter: https://liveexample.pearsoncmg.com/html/TestRandomCharacter.html