Methods don't only get called from main — one method can call another. A method that does a small job for another is a helper. Calling helpers lets you build a bigger result out of smaller, tested pieces.
main
int square(int n) { return n * n; } int sumOfSquares(int a, int b) { return square(a) + square(b); // calls the helper twice } System.out.println(sumOfSquares(3, 4)); // 9 + 16 = 25
▶ Try it: sumOfSquares calls the helper square. Run this, then change the two arguments and re-run.
sumOfSquares
square
square(n) returns n * n. sumOfSquares(a, b) returns square(a) + square(b). What does sumOfSquares(3, 4) give?
square(n)
n * n
sumOfSquares(a, b)
square(a) + square(b)
sumOfSquares(3, 4)
Can one method call another method?
Assemble the body of sumOfSquares using the helper square.
True or false?
Type exactly what this program prints.
public class Main { static int half(int n) { return n / 2; } static int halfSum(int a, int b) { return half(a) + half(b); } public static void main(String[] args) { System.out.println(halfSum(10, 6)); } }