Introduction to Software Development
GWU Computer Science
By the end of this module, for simple HelloWorld-like programs, you will be able to:
In the previous module with Strings, we practiced using methods that resolve (or return) something and that might need input parameters to run.
In this segment we'll practice writing and invoking such methods.
First, three definitions:
void
return type means the method does not return anything, and you can skip having a return
statement. However, the return type can be any valid type (such as int
or String
) and if it is specified on the method declaration line, you must have a return
statement that returns something of that type from every possible path through your method: the compiler enforces this.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class IOMethods1 { public static void main(String args[]) { int num1 = 5; int num2 = 3; // Invoke the myOperation method and save result in the num3 variable int num3 = myOperation(num1, num2); // myOperation(num1, num2) resolves into the resulting value System.out.println ("myOperation on " + num1 + " and " + num2 + " is: " + num3); } public static int myOperation(int num1, int localNum2) { num1 = num1 + 1; localNum2 = localNum2 + 1; int localNum3 = (num1 * localNum2); // this causes the method invocation to resolve into localNum3 return localNum3; } } |
Let's trace through this code on paper to understand what's happening with the different variables and arguments. Take notes! We don't list the details here on the slides (so that you take notes), but make sure you understand what scope is by the end of the lecture.
You may have seen variables that were declared outside methods in our homework (for example, turning a test case on or off) -- these were used to
control whether or not a problem gets tested. You may have observed that our main
method
was able to see these variables, even though they were declared outside of the method. Let's formally
explore what's going on now with some live examples showing how variables can be shadowed when a method declares an variable with the same
name and type as a field that lives outside all of the methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class IOMethods1 { // ignore the static keyword for now (we'll learn more about static next class) static int num1 = 11; static int num4 = 3; public static void main(String args[]) { int num2 = 3; // Invoke the myOperation method and save result in the num3 variable int num3 = myOperation(num1, num2); // myOperation(num1, num2) resolves into the resulting value System.out.println ("myOperation on " + num1 + " and " + num2 + " is: " + num3); num4++; } public static int myOperation(int num1, int localNum2) { num1 = num1 + 1; localNum2 = localNum2 + 1; int localNum3 = (num1 * localNum2); // this causes the method invocation to resolve into localNum3 return localNum3; } } |