Java Methods (Subgoal-Labeled Worked Examples)
Java Methods (Subgoal-Labeled Worked Examples)
Problem: Write a method that sums two integers and prints their sum. Call the method with two integers.
class Main {
public static void main(String[] args) {
}
}
1. After the main method ends, write “public static void” followed by the name of your new method.
class Main {
public static void main(String[] args) {
2. Write the comma-separated parameters for the method, including the data types and the parameter
names.
class Main {
public static void main(String[] args) {
}
3. Add in the curly braces.
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
}
SUBGOAL: Call the method.
class Main {
public static void main(String[] args) {
sum
}
2. Add parentheses after the method name to call it. Inside the parentheses, include the two arguments.
End with a semicolon.
class Main {
public static void main(String[] args) {
sum(2, 3);
}
Problem: Write a method that sums two integers and returns their sum. Call the method with two integers
and store the result in a variable.
class Main {
public static void main(String[] args) {
}
}
1. Write “public static” followed by the data type of the return variable and the name of the method.
class Main {
public static void main(String[] args) {
2. Write the comma-separated parameters for the method, including the data types and the parameter
names.
class Main {
public static void main(String[] args) {
}
3. Add in the curly braces.
class Main {
public static void main(String[] args) {
4. Write the body of the method, ending with a return statement followed by a value.
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
int number
}
class Main {
public static void main(String[] args) {
int number = sum(2, 3);
}
3. Optional: you can print the variable to see what’s inside it!
class Main {
public static void main(String[] args) {
int number = sum(2, 3);
System.out.println(number);
}