public class EX01_TestMax { 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); } /** Return the max between two numbers */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } }
int z = max(a, b);
p.181 Figure 5.1 A method definition consists of a method header and a method body
參考 p.182 程式 Listing 5.1 TestMax.java
p.138 Figure 5.2 when the max method is invoked, the flow of control transfers to it. Once the max method is finished, it returns control back to the caller
p.183 Caution return
public static int sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else // else if (n < 0) will compiler error return -1; }
p.184 Figure 5.3 Call Stacks
參考 p.184 程式 Listing 5.2 TestVoidMethod.java
參考 p.185 程式 Listing 5.3 TestReturnGradeMethod.java
參考 p.187 程式 Listing 5.4 Increment.java
參考 p.187 程式 Listing 5.5 TestPassByValue.java
參考 p.189 程式 Listing 5.6 GreatestCommonDivisorMethod.java
參考 p.190 程式 Listing 5.7 PrimeNumberMethod.java
參考 p.191 程式 Listing 5.8 Decimal2HexConversion.java
System.out.printf("decimail %1$d = %1$X \n", decimal);
參考 p.193 程式 Listing 5.9 TestMethodOverloading.java
p.195 Figure 5.5 Variable Scope
p.195 Figure 5.6 A variable can be declared multiple times in nonnested blocks but only once in nested blocks
p.195 Caution Do not declare a variable inside a block and then attempt to use it outside the block
r = (int) (Math.random() * 10); // 0..9 r = 50 + (int) (Math.random() * 50); // 50..99 r = a + (Math.random() * b); // [a, b)
參考 p.199 程式 Listing 5.10 RandomCharacter.java
參考 p.200 程式 Listing 5.11 TestRandomCharacter.java
p.201 Figure 5.8 Black Box
p.202 Figure 5.9 PrintCalendar(readInput, printMonth(printMonthTile, printMonthBody))
參考 p.205 程式 Listing 5.12 PrintCalendar.java