CS 1110/1111: Introduction to Programming

Lecture 21

Announcements

HW5 will start after the break and will be done in pairs.

Talking Points

See these slides.

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

Because Java passes a method values as its arguments (i.e., copies of what was in the variable, not the variable itself) there is no way to write a swap method:

public static void swapAttempt(int a, int b) {
    System.out.println("Swap attempt called with " + a+", "+b);
    int c = a;
    a = b;
    b = c;
    System.out.println("Swap attempt finished with " + a+", "+b+", "+c);
}
public static void main(String[] args) {
    int a = 3;
    int b = 4;
    int c = 5;
    System.out.println("Main has " + a + ", " + b + ", " + c);
    swapAttempt(a,b);
    System.out.println("Main has " + a + ", " + b + ", " + c);
    swapAttempt(b,a);
    System.out.println("Main has " + a + ", " + b + ", " + c);
}

Practice

Try Coding Bat to practice writing methods.

Copyright © 2014 by Luther Tychonievich. All rights reserved.