Skip to content

Week 7 - Methods Take 2

Methods Take 2

Why We Create Methods

  • Methods are directly related to the actions (VERBS) performed on our classes/OBJECTS (NOUNS)
    • Class/Object: Car / car1
    • Method: turnCar
  • Methods allow us to re-use code.
    • e.g. Scanner let’s us get input of different Data Types (int, double, String), without us having to re-write the data-type conversions or the code to read from InputStreams like stdin (i.e. System.in).
  • Methods encapsulate complex algorithms so we can ignore the details and simply trust the method to do its job.
    • e.g Math.toRadians, Math.pow, Math.toDegrees: we trust these static methods to do what they say even though we may not know how to implememnt them ourselves.
  • Methods allow us to break up bigger problems into smaller, more understandable units (i.e. functional decomposition).
    • Think about our car action of turn. We could implment it all in 1 method that says:
      1. Driver places hands on wheels
      2. Drive turns steering wheel 25 degrees to the left
      3. Hydraulic assist system in rack and pinion mechanism takes rotational motion energy and converts it into linear motion energy
      4. Linear motion energy is transfered to the wheels
      5. wheels turn at an angle proportional to that of the 25 degree turn of the steering wheel
    • OOORRR, we could acknowledge that each one of these statements is housed within its own Classes (Driver, Steering Wheel, Rack and Pinion, Wheels), and we could divide the actions into methods in each of those classes allowing us to functionally decompose the process of turning.
      • Driver: movesHands(Position p) rotatesWheel(SteeringWheel s, Force f, Direction v)
      • SteeringWheel: rotate(Direction rl, Degree d)

Review Method Signature / Static VS Public

Excercise 1

Create a method called printText which prints the phrase “In a hole in the ground there lived a [animal]” where [animal] is replaced by a parameter passed in, then a newline is printed.

Answer 1
1
2
3
public static void printText(String anmimal) {
    System.out.printf("In a hole in the ground there lived a %s%n", animal);
}

Method Parameters

  • Information passed to methods
1
2
3
public void rotateWheel(Direction rl, Degrees d) {
    ....
}
  • Comes between the open and close parenthesis
  • Multiple parameters are separated by commas
  • Can be basic types, objects, or arrays (think lists) of these things

Return Types

  • How we get data back out of our methods.
1
2
3
4
public Position rotateWheel(Direction rl, Degrees d) {
    ....
    return new Position(x, y, z);
}
  • Must return the same datatype noted in the return type of the method signature
  • Return type can be basic types, objects, or arrays of these things
  • You can return null
Excercise 2

Create a method called sum that takes 2 integer parameters and returns their summation.

Answer 2
1
2
3
public static int sum(int first, int second) {
    return first + second;
}
Excercise 3

Create a method called divisibleByThree that takes an integer and returns whether or not it is divisible by three.

Answer 3
1
2
3
public static boolean divisibleByThree(int number) {
    return ((number % 3) == 0);
}

Scope

  • Class scope
    • Variables and methods in the Class scope will persist as long as the class and or objects of that class persist.
    • They can be masked by Method scoped variables.
      • Consider constructing a Car object with Field color where the constructor takes a parameter color.
  • Method scope
    • Once you return from a method, any variables locally declared in that method disappear.
Excercise 4

Consider the following main method and its call to incrementByThree. Will the number variable in main be altered after the incrementByThree method call returns?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// main program
public static void main(String[] args) {
    int number = 1;
    System.out.println("The value of the variable 'number' in the main program: " + number);
    incrementByThree(number);
    System.out.println("The value of the variable 'number' in the main program: " + number);
}

// method
public static void incrementByThree(int number) {
    System.out.println("The value of the method parameter 'number': " + number);
    number = number + 3;
    System.out.println("The value of the method parameter 'number': " + number);
}

Excercise 5

Now consider the following main method and its call to incrementByThree. Will the number variable in main be altered after the incrementByThree method call returns?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class IntegerTests {
    // main program
    public static void main(String[] args) {
        MyInt number = new MyInt(3);
        System.out.println("The value of the variable 'number' in the main program: " + number);
        incrementByThree(number);
        System.out.println("The value of the variable 'number' in the main program: " + number);
    }

    // method
    public static void incrementByThree(MyInt number) {
        System.out.println("The value of the method parameter 'number': " + number);
        number.add(3);
        System.out.println("The value of the method parameter 'number': " + number);
    }
}

Answer 5

Assuming MyInt looks something like below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class MyInt {
    private int value;

    public MyInt(int value) {
        this.value = value;
    }

    public void add(int value) {
        this.value += value;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }
}

Then the internal non-static field of value will be altered by the incrementByThree method call because the number is an object, and objects get passed by reference. Thus, anything that alters the state of the object, even if in another method, will affect the internal fields of the passed object. Let’s see it in action…

Exercise 6

What does the program below print?

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
    int number = 10;
    modifyNumber(number);
    System.out.println(number);
}

public static void modifyNumber(int number) {
    number = number - 4;
}

Answer 6

10

Overloading Methods

  • We saw this last week with constructors, but you can overload ANY method.
  • This just means the method name stays the same, but the parameter list changes.
    1
    2
    3
    4
    5
    6
    7
    public static int greatest(int number1, int number2) {
        return (number1 > number2) ? number1 : number2;
    }
    
    public static double greatest(double number1, double number2) {
        return (number1 > number2) ? number1 : number2;
    }
    
  • Overloading by w3schools
Exercise 7

Write a method that compares two integers and returns the smallest integer. Then overload the method for two double numbers.

Answer 7
1
2
3
4
5
6
7
public static int smallest(int number1, int number2) {
    return (number1 < number2) ? number1 : number2;
}

public static double smallest(double number1, double number2) {
    return (number1 < number2) ? number1 : number2;
}