CS 1054: Laboratory Exercise 4

Objective

This exercise's objective is to familiarize you with the use of methods in Java.

To Receive Credit

You will write a few methods in this lab. After writing them all, show your results to the instructor.

Activities

After launching the Eclipse IDE, create a new project and name it Lab4. Create a class within this project called LabExercise4. In the pop-up window for specifying the name of this class, do not click on the check-box next to the option for creating the main method. Within this class, do the following tasks.

  1. In the previous lecture, we talked about methods and how to define and use them within a Java program. For example, the method below finds the larger number out of two numbers.
    public static int max(int num1, int num2) {
    
    int result;
    
    if (num1 > num2)
      result = num1;
    else
      result = num2;
    
    return result;
    }
    
    Note the name of the method, its parameters and its return value. The proper way of invoking this method from within another method is:
    int z = max(x, y);
    
  2. Within the body of the LabExercise4 class, comment everything out and write a simple method to calculate the sum of three numbers. The method should be called addThreeNumbers and it should return an int value which is the sum of the three numbers. The method should accept three formal parameters of type int. Invoke this method from within the main method and see if it works correctly. Test it by providing different values for the three actual parameters and seeing if the returned value is indeed the sum of these three numbers. Show your work to the instructor.
  3. What happens if you provided numbers or variables of type double to the function? Does it work correctly? If not, modify the formal parameters of the function to make it accept doubles? Test it now. You might see the sum being truncated when it is returned back to the calling method. To rectify this problem, change the return type of the method to double. Test it again. Show your work to the instructor.
  4. Understanding pass by value: Within the body of the LabExercise4 class, comment all the code that is present and type or copy/paste the following code:
      public static void main(String args[]) {
        int max = 0;
        findmax(1, 2, max);
        System.out.println("max = " + max);
      }
      
      public static void findmax(int num1, int num2, int max) {
        if (num1 < num2) 
          max = num2;
        else
          max = num1;
      }
              
    Write down the output that this program produces after running it. What value did you expect? What value did the program actually produce? The reason for the answer that you see is the pass-by-value mechanism of parameter passing that is employed by Java. Show the result of running the program to the instructor.

© Mir Farooq Ali 2005.