0% found this document useful (0 votes)
0 views61 pages

COMP1010_Week04_VideoSlides

Week 4 of COMP 1010 focuses on understanding and implementing methods in programming, including the use of parameters and return values. Key learning objectives include subdividing complex problems into subroutines, identifying variable scope, and emphasizing the importance of testing methods. The document also covers user-defined methods, method signatures, and the run-time stack for managing method variables.

Uploaded by

raghav.k271205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views61 pages

COMP1010_Week04_VideoSlides

Week 4 of COMP 1010 focuses on understanding and implementing methods in programming, including the use of parameters and return values. Key learning objectives include subdividing complex problems into subroutines, identifying variable scope, and emphasizing the importance of testing methods. The document also covers user-defined methods, method signatures, and the run-time stack for managing method variables.

Uploaded by

raghav.k271205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

COMP 1010:

Introductory Computer Science 1


WEEK 4

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
LEARNING OBJECTIVES

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Week 4 Objectives
• Subdivide complex problems into subroutines (methods).
• Implement subroutines with parameters and return values.
• Identify the scope of local variables.
• Describe the uses of variables of different scope.
• Explain the importance of testing each method and writing one method at a
time.
• Identify test data to thoroughly test a method for average/typical cases as well
as special/edge cases.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 1: INTRODUCTION TO METHODS

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Methods
• We have already seen and used methods:
◦ System.out.println("Hello") println() is a method
◦ Math.sqrt(5) sqrt() is a method
◦ s.charAt(3) charAt() is a method

• What is going on behind the scenes? How do methods work?

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Methods
• When a method is called:
◦ Program pauses at the location of the method call
◦ Control jumps to the method
◦ The method runs
◦ Optionally, a value is sent back from the method
◦ Program continues where it left off
class Test{
public static void main(String[] args){
double x = Math.sqrt(25);
System.out.println("The answer is " + x);
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Methods
• Do ONE task
◦ Should be SHORT
• Are used to break up problems into small, well-defined, pieces
• Are reusable
◦ Write the code once, and reuse it many times
• Result in more readable code that is easier to maintain

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
User-Defined Methods
• Syntax:
static <return type> methodName(<list of parameters>){
<method body>
}
• Naming convention: method name starts with lowercase (same as variable names)
◦ Additionally: first word is usually a verb (printMessage, calculateTax, getInput, findMaximum), giving
you an idea of what the method will do
• Return type: data type to be returned from the method, or void if method doesn’t return anything
• List of parameters: data to be passed to the method (data type + name for each, same as variable
declarations)
◦ Optional
◦ Comma-separated
• Method body is the block of code inside { } that is run when the method is called

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The method signature
• The name of the method, return type, and data types of parameters

• Note: This is not quite the same as the "header" of the method, which refers
to the entire first line of a method, including parameter names.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Example: User-Defined Method
class MethodTest{
public static void main(String[] args){
System.out.println("This is printed before my method runs.");
printMessage();
Note: User- System.out.println("This is printed after my method runs.");
defined methods
}
are in the same
class { } as main.
static void printMessage(){
System.out.println("This is a message I want to print.");
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Methods Can Call Other Methods
• The method body can include any statements, including calls to other methods.
User-defined methods:
static void printStart(){
System.out.println("This is the start.");
}
static void printEnd(){
System.out.println("This is the end.");
}
static void printStuff(){
printStart(); //call another user-defined method
System.out.println("This is the middle.");
printEnd();
}
In main:
printStuff(); //To call methods without parameters, leave () empty.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Methods
• Code order:
◦ The order of method definitions within a class does not matter. Your program starts
running at main, whether it is the first method (at the top of the class) or not.
◦ Convention: main first (at the top of the class), so that we can easily find it to see
what the program does

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Programming Standards: Commenting
Methods
• In a comment at the top of each user-defined method, list:
◦ The purpose of the method (What does the method do?)
- e.g. "Calculate the sum of a list of numbers.", "Get a number between 1 and 10 from the
user.", "Find the smallest value in a list of numbers."
◦ Description of parameters (What does the method's user need to send it?)
- List each parameter and explain Omit if there are
e.g. double price – price of the item for which to calculate tax no parameters
◦ Return value (What does the method return?)
- Explain what the user can expect to get as a result Omit if nothing is
- e.g. double – the price of the item, after adding tax returned
◦ If the method uses or alters any globals, clearly state that. If not stated, the user will
expect that no globals are accessed.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Programming Standards: Commenting
Methods
• Someone using your methods shouldn't need to read and decipher every
line of code to understand how to use your method.
• Provide a comment with sufficient detail that someone can use your
method without examining the code inside the method.
/* calculateTax
* Purpose: Calculate the price after tax.
* Parameters: price – the price of an item before tax
* Return: double – the price of the item after tax
* Global used: TAX_RATE
*/
static double calculateTax(double price){
double priceWithTax = price * (1.0 + TAX_RATE);
return priceWithTax;
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 2: METHODS WITH PARAMETERS

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Passing Data
• Sometimes we want to pass data to our methods:
◦ Send the method information to be used in the method body.
◦ Each time the method runs, it can be sent different information. When defining the
method: Specify type and
name for each parameter
static void printInfo(String name, int age){
System.out.println(name + " is " + age + " years old.");
} When calling the method:
In main: Pass data of the specified
(or compatible) type
printInfo("John", 25);
printInfo("Alice", 21);

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Terminology
• A parameter is a variable in the method definition.
◦ E.g. The definition of println is public void println(String x) – x is a parameter
◦ E.g. The definition of sqrt is static double sqrt(double a) – a is a parameter
• An argument is a value that is passed to the method when it is called.
◦ E.g. In System.out.println(“Hello”); the String “Hello” is an argument
◦ E.g. In Math.sqrt(20); the number 20 is an argument

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
User-Defined Method with Parameter
class MethodTest{
public static void main(String[] args){
System.out.println("This is printed before my method runs.");
printMessage("The message to print");
System.out.println("This is printed after my method runs.");
}
static void printMessage(String message){
System.out.println(message);
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
User-Defined Method with Parameter v2
class MethodTest{
public static void main(String[] args){
System.out.println("This is printed before my method runs.");
String s = "The message to print";
printMessage(s); //To call a method with parameters, list them in
//the same order as in the signature

System.out.println("This is printed after my method runs.");


}
static void printMessage(String message){
System.out.println(message);
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Example with Several Parameters
class MethodTest{
public static void main(String[] args){
int x = 5;
double y = 3.2;
printProduct(x, y); //To call a method with parameters, list them in
//the same order as in the signature
}
static void printProduct(int a, double b){
double c = a * b;
System.out.println("The product is " + c);
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
• How does your computer keep track of which variables are in which method?
• Each method has its own collection of variables
• When a method starts, storage for the parameters is allocated
• As a method runs, if local variables are declared they are added to the
collection
• When a method ends, the method's variables disappear

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int a){
int b = 8;
anotherMethod(b, a);
}
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!");
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int a){
int b = 8;
anotherMethod(b, a);
}
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod n 8
public static void main(String[] args){
int x = 5, y = 6; m 5
myMethod(x);
}
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod n 8
public static void main(String[] args){
int x = 5, y = 6; m 5
myMethod(x);
} z 10
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod n 8
public static void main(String[] args){
int x = 5, y = 6; m 5
myMethod(x);
} z 10
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod n 8
public static void main(String[] args){
int x = 5, y = 6; m 5
myMethod(x);
} z 10
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod n 8
public static void main(String[] args){
int x = 5, y = 6; m 5
myMethod(x);
} z 10
static void myMethod(int a){
int b = 8;
myMethod a 5
anotherMethod(b, a);
}
b 8
static void anotherMethod(int n, int m){
int z = 10;
System.out.println("Hello!"); main x 5
}
} y 6

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int y){
int x = 8;
y = 14;
anotherMethod(x, 3);
}
static void anotherMethod(int x, int y){
int z = 10;
System.out.println("Hello!");
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int y){
int x = 8;
y = 14;
anotherMethod(x, 3);
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int y){
int x = 8;
myMethod y 5
y = 14;
anotherMethod(x, 3);
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int y){
int x = 8;
myMethod y 5
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{
public static void main(String[] args){
int x = 5, y = 6;
myMethod(x);
}
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod x 8
public static void main(String[] args){
int x = 5, y = 6; y 3
myMethod(x);
}
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod x 8
public static void main(String[] args){
int x = 5, y = 6; y 3
myMethod(x);
} z 10
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod x 8
public static void main(String[] args){
int x = 5, y = 6; y 3
myMethod(x);
} z 10
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod x 8
public static void main(String[] args){
int x = 5, y = 6; y 3
myMethod(x);
} z 10
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
The Run-Time Stack
class MethodTest{ anotherMethod x 8
public static void main(String[] args){
int x = 5, y = 6; y 3
myMethod(x);
} z 10
static void myMethod(int y){
int x = 8;
myMethod y 14
y = 14;
anotherMethod(x, 3);
x 8
}
static void anotherMethod(int x, int y){
int z = 10; main x 5
System.out.println("Hello!");
} y 6
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 3: METHODS THAT RETURN VALUES

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Return Statements
• Are used to send data back to the caller
• Send back ONE thing
• The data type of the thing sent back must be compatible with the declared
return type
• Are optional for void methods

static String getMessage(){


return "A very interesting message.";
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Capture the Returned Data
• The returned value should be captured (used immediately or saved for
later use)

System.out.println(getMessage()); //immediately use the


//String from the method

String myMessage = getMessage(); //get a String from the


//method and save it for later

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Where to Return?
• Return statements should almost always be the last line in a method

• A return statement ends the method immediately

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Return is Optional for Void Methods
• Ends the method immediately

static void printStuff(){


System.out.println("stuff");
}
is the same as
static void printStuff(){
System.out.println("stuff");
return;
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Example: Method to Get Number From User
import java.util.Scanner;
class MethodTest{
public static void main(String[] args){
Scanner keyIn = new Scanner(System.in);
int x = getInt(keyIn);
System.out.println("The first number is " + x);
int y = getInt(keyIn);
System.out.println("The second number is " + y);
keyIn.close();
}
static int getInt(Scanner s){
System.out.print("Please enter an integer: ");
String input = s.nextLine();
int num = Integer.parseInt(input); or,
return num; int num = s.nextInt();
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Method Overloading
• Methods can have the same name, as long as they have different signatures
◦ Different number of parameters, or
◦ If they have the same number of parameters, there is at least one position where the data
type is different.
• Usage determines which version is called
◦ Which method had parameter data types that are compatible with the data passed?

static int sumTwo(int a, int b){ return a + b; }


static double sumTwo(int a, double b){ return a + b; }
static double sumTwo(double a, double b){ return a + b; }

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 4: VARIABLES & SCOPE

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Scope
• The scope of a variable is the part (lines) of a program where the variable
exists and can be used.

public static void main(String[] args){


System.out.println("some output");
// we can't use x here before it is declared – the computer
// doesn't yet know what x is
int x = 10; // x first exists here
scope of x
int y = 5 * x + 2; // we can use x after it is declared
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Local Variables
• Method parameters are only visible/accessible within the method.

class Example{
public static void main(String[] args){
//x is undefined here
}
static double getTotal(double x){
scope of x //x can be used here
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Local Variables
• Variables defined/created inside a method are only visible within the
method, from the point the variable is created until the end of its scope
◦ For now, end of scope is end of method, but see blocks (e.g. loops) & nesting later.

class Example{
public static void main(String[] args){
//x is undefined here
}
static void doSomething(){
int x = 123;
scope of x //x can be used here
}
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Global Variables & Global Constants
• Because Java is an object-oriented language (see COMP 1020), everything is
part of a class.
• We can place variables or constants OUTSIDE of all methods, making them
available everywhere within the class.

• Note: In other languages, we have true global variables & constants, which
are available everywhere in the program. In Java, we are actually creating
class-level variables & constants. For our purposes (programs with one class),
we'll refer to these as global. See COMP 1020 for more detail.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Global Constants
• Does your program have a value that doesn't change in the program, and is needed
by many different methods?
◦ Instead of declaring in each method, use a global constant.
◦ Convention: Place constants at the top of the class, before the main method

class TaxExample{
static final double TAX_RATE = 0.05; // 5%
public static void main(String[] args){ … }
static double getTotal(double price){ return price*(1+TAX_RATE); }
static double getTax(double price){ return price*TAX_RATE; }
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Global Variables
• Does your program have a value that changes in the program, and is used by many
different methods?
◦ You could use a global variable - That is often bad practice though.
- It's hard to predict the value at any point in time, because you need to consider which
methods have accessed & changed it.
- Often, it's better to pass data to & from methods.

class Game{
static int score = 0; // set initial value
public static void main(String[] args){ … }
static void destroyMonster(){ … score += 10; … }
static void findTreasure(){ … score += 100; … } //all methods change
static void getLost(){ … score -= 25; … } //the same variable
}

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Scope
• Keep the scope of a variable as small as possible
◦ If only needed in one method/block, declare it in that method/block.
• Be careful not to shadow (hide) other variables
◦ If a variable declared in a method has the same name as a global variable, the local
variable is the one that will be accessed when you use the variable name in that
method.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 5: PROGRAM DEVELOPMENT & TEST DATA

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Incremental Development
• What happens if you write 200 lines and your program doesn't compile?
◦ Potentially many errors to correct.
◦ Error messages from the compiler will help.
◦ Not fun.

• What if you correct the syntax errors, the program compiles, but the output isn't
correct?
◦ Where to look for the problem?
◦ Debugging many lines can be VERY difficult.

• If you write and thoroughly test one method at a time, the problem is likely in the last
method you wrote (and much easier to find).

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Incremental Development
• Write ONE method at a time:
◦ Make a list of the methods your program will need.
◦ Write and test each method individually (you could use a separate .java file to do this).
◦ Then combine the methods into the final program.

• Within each method:


◦ Make a list of the steps the method should do.
◦ Write the code for one step at a time.
◦ Test the code for one step before writing the code for the next step.

• Test often!

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Test Data
• Test your methods for all possible values/inputs
◦ Think about "general cases" and "edge cases" or "special cases".
◦ E.g. If a method is valid for the numbers 1 to 10:
- Test with 1, test with 10, and test with something in the middle.
- Also test with invalid numbers.
- Consider what your method should do if given invalid input. Crash? Return 0? Return -1? …

• When testing, isolate and test ONLY the method of interest.


◦ Pass literals rather than variables initially.

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
COMP 1010: Week 4
VIDEO 6: INCREMENTAL DEVELOPMENT DEMO: PROCESS NAME

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.
Write A Program That…
• Asks the user to input their name (first, space, last)
• Identify their first and last names
• Print a greeting

• See ProcessName.java

Fall 2023 Edition ALL SLIDES © THEIR RESPECTIVE AUTHORS; REDISTRIBUTION IS NOT PERMITTED.

You might also like