# Java: Method Exercises 2

Name: _________________________________

What is the output from this program? Write answers on back of this sheet.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
    // methods/exercises/MethodExercises2 - What is the output?
    // Fred Swartz - 2004 September
    // Remember:
    // * If a method is overloaded (more than one method by the same name),
    //   choose the one with the same number and types of parameters.
    // * Actual parameters (in the call) are evaluated before the method
    //   is called.  This includes making calls within the parameter list.

    import javax.swing.*;

    class MethodExercises1 {
        public static void main(String[] args) {
            int n;

            output("Greetings");
            output(32);
            output("Unix era started in ", 1970);
            n = add(3, 2);
            output("The sum is ", n);
            output(something(8, 4));
            output("Ulam(20) = ", ulam(20));
            output("Ulam(5) = " , ulam(5));

            System.exit(0);
        }

        /** Displays an integer by calling another method. Overloaded, */
        static void output(int i) {
            output("Result = ", i);  // Calls one of the other output methods.
        }

        /** Displays a String, Overloaded. */
        static void output(String mess) {
            JOptionPane.showMessageDialog(null, mess);
        }

        /** Displays a message and an integer. Overloaded. */
        static void output(String message, int i) {
            output(message + i);  // Calls one of the other output methods.
        }

        /** Returns the result of adding the first parameter to second. */
        static int add(int a, int b) {
            return a + b;
        }

        /** Returns something. */
        static int something(int a, int b) {
            if (a > b) {
                return a;
            } else {
                return b;
            }
        }

        /** Computes next value in Ulam sequence. */
        static int ulam(int x) {
            int result;
            if (x%2 == 0) {
                result = x / 2;   // If number is even, divide it by 2
            } else  {
                result = 3*x + 1; // Odd numbers processed here.
            }
            return result;
        }
    }