-
Give students code that includes multiple methods to help students bridge this jump.
-
Have students trace through the provided code.
-
Then, have students write code for a program that uses multiple methods (like in the example activities below).
-
Activity 1:
-
Provide students with the following code to trace through, individually or in groups.
-
As a class, trace through the code together to make sure everyone correctly understands the order the code executes in.
public class ExampleClass {
public static void main(String[] arg){
System.out.println("Hello!");
ExampleClass.function1();
ExampleClass.function2();
}
public static void function1(){
System.out.println("in function1");
ExampleClass.function3();
}
public static void function2(){
System.out.println("in function2");
}
public static void function3(){
System.out.println("in function3");
}
}-
Activity 2:
-
Have students write code to calculate the sum of squares using the following instructions.
-
Write a method named
square
, which takes in an int as an argument and returns the square of the number: -
public static int square(int x)
-
Next, write a method
sumOfSquares
that takes in two ints as arguments and returns the sum of squares. public static int sumOfSquares(int a, int b)
- Here is some example code:
public class MathHelper {
public static void main(String[] arg){
System.out.println("Hello!");
int output = sumOfSquares(3, 4);
System.out.println("sumOfSquares(3, 4) returns " + output);
}
public static int sumOfSquares(int a, int b){
return square(a) + square(b);
}
public static int square(int x){
return x * x;
}
}