Full Stack
🗙
So+ware Engineering
🗙
Java Methods
By Max Wong
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
2
What will you learn?
• Understand what are methods
• Methods with different return type
• Understand the use cases of creating methods
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
3
Method Declara4on (1)
public class MathUtility {
.....
public static void sayHello() { Method Signature
.....
}
.....
}
Access specifier
Op5onal Modifier(s)
Return type
Method name
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
4
Calling a Method
public class MethodCall { • The way we call a method is to
write its name followed by a pair
public static void main(String [] args) { of ().
[Link]("In main");
• When a method is called, the
sayHello(); program flows to execute the
[Link]("Back to main");
method and the caller suspends.
} • When execu>on reaches the
closing brace ( } ), the method
terminates.
public static void sayHello() { • The program then flows “back”
[Link]("Hello"); to the caller.
}
} Forget about “public static” at the moment
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
5
The return Statement
public class MethodReturn {
public static void main(String [] args) {
• Another way to terminate a
[Link]("In main"); method execu8on is by using
sayHello();
[Link]("Back to main");
the return statement.
} • Whenever execu8on reaches
public static void sayHello() { the return statement, the
if (...) method terminates. (No
return;
[Link]("Hello"); ma@er where the return
} appears in the method.)
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
6
Method Declara1on (2)
public class MathUtility {
.....
public static void showValue(double in) { Method Signature
.....
}
.....
}
Access specifier
Op5onal Modifier(s)
Return type
Method name
Optional parameters
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
7
Parameter Passing
public class SingleParameter { • When calling a method, a parameter can be
provided, 30 in this example.
public static void main(String [] args) {
• The method receiving the parameter must
showValue(30); 30 have a variable to store the parameter data.
}
• When the method is entered, the parameter
variable is created.
public static void showValue(int value) {
[Link]( value ); 30 • When the method terminates, the
parameter variable is destroyed.
} value
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
8
Mul1ple Parameters
public class MultipleParameters {
• Mul>ple parameters can be sent
public static void main(String [] args) {
to the method.
showSum(1, 2);
2
} 1 • Of course, the number of
parameters must match, and the
public static void showSum(int x, int y) { corresponding parameters must
[Link]( x + y ); have the same data type.
}
1 2
x y
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
9
Local Variables
public class LocalVariables { • A method can define its own
public static void main(String [] args) { variables.
showSum(1, 2);
2 • Such variables can only be used
}
1 within the method.
public static void showSum(int x, int y) { • For this, they are called local
int sum; 3 1 2 variables.
sum = x + y; sum x y
[Link]( sum ); • Local variables are created upon
} entering and destroyed upon
}
leaving the method.
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
10
public class VoidMethodExamples {
public static void main(String [] args) {
sayHello();①
Examples
showValue(30); ②
showSum(1, 2); ③
Hello
showSum2(3, 4); ④
30
discount(100, 0.9);⑤ 3
}
7
① 90.0
public static void sayHello() {
[Link]("Hello"); ③④⑤
} ④
② public static void showSum2(int x, int y) {
public static void showValue(int value) { int sum;
sum = x + y;
[Link](value);
[Link](sum);
} }
③ ⑤
public static void showSum(int x, int y) { public static void discount(int amount, double rate) {
[Link](x+y); [Link](amount * rate);
} }
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
11
Method Declara1on (3)
public class MathUtility {
.....
public static int showSum(int x, int y) { Method Signature
.....
}
.....
}
Access specifier
Op5onal Modifier(s)
Return type
Method name
Op5onal parameters
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
12
Method Return Value
public class ReturnIntMethod {
public static void main(String [] args) { • A method may send back a reply
int sum; to the caller, that is, “returning”
the result.
3 sum = showSum(1, 2);
[Link]("Sum = " + sum);
• In this example, return sum
} 1 2 returns the value 3 to the caller.
public static int showSum(int x, int y) {
• Since the method produces an int
int sum; 3 1 2
sum = x + y;
result, its type is defined as int.
sum x y
return sum;
}
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
13
Function Return Value in Detail
public class ReturnIntMethod {
public static void main(String [] args) {
int sum; 3 Note that variable sum in main()
3 and variable sum in showSum() are
sum = showSum(1, 2); sum
two different variables.
[Link]("Sum = " + sum);
} 3
public static int showSum(int x, int y) {
int sum;
3 1 2
Main showSum
sum = x + y;
sum x y
Sum x, y, Sum
return sum;
}
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
14
Summary of the return Statement
• When a return is encountered, program execution flows back to where it
was called.
• The first form: return;
• is used when the method produces no value.
• The type of the method must therefore be void.
• The second form: return expression;
• is used when the method return a value (expression).
• The data type of expression must be the same as the method type (not void).
• Conversely, when the method type is not , there must be at least one return
expression; statement with the correct expression data type.
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
15
In-class Exercise
Are they correct?
public static void myMethod() { public static int myMethod() {
}
... ❌ /✔ }
... ❌ /✔
public static void myMethod() { public static int myMethod() {
...
return; ❌ /✔ ...
return; ❌ /✔
} }
public static void myMethod() { public static int myMethod() {
...
return x; ❌ /✔ int x;
... ❌ /✔
} return x;
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
16
In-class Exercise
Are they correct?
public static int myMethod() { public static int myMethod() {
float x;
... ❌ /✔ int x;
float y; ❌ /✔
return x;
} ...
if (...)
return x;
else
return y;
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
17
Pass-by-Value
All variables in primitive data type duplicate its value to the called method
public class CallByValue {
No ma=er how the
public static void main(String [] args) {
int number = 10; 10 value is updated in
the method square,
number
square(number); the number in the
method main is not
Duplicate
[Link]("number in method main: " + number);
} affected.
public static void square(int number) {
10
New variable
number
number *= number;
[Link]("number in method square: " + number);
}
} number in method square: 100
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab Number in method main: 10
Can you tell me when should we
create methods?
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
19
Use Case of Crea1ng Methods
Reuse of codes (Don’t Repeat Yourself Principle):
Be alert when you are trying to Copy & Paste your
codes. This ac5on is possibly telling you that you should
create a method for your copying codes.
Don’t copy any code before asking yourself why you cannot reuse
the code.
Risk of Copy-and-Paste Programming:
• Low readability
• Hard to update logics as there are mulCple instances
throughout the project
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
20
Use Case of Crea1ng Methods
Wrap a bunch of code with explicit usage
Instead of using comments, wrap the code with explicit usage (e.g. find
the max number, print a full-diamond, etc.) can helps your code to
self-explain its usage.
Enhance readability
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
21
What did you learn?
• Understand what are methods
• Methods with different return type
• Understand the use cases of crea8ng methods
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab