Object-Oriented Programming with Java, part I + II

cc

This material is licensed under the Creative Commons BY-NC-SA license, which means that you can use it and distribute it freely so long as you do not erase the names of the original authors. If you make changes in the material and want to distribute this altered version of the material, you have to license it with a similar free license. The use of the material for commercial use is prohibited without a separate agreement.

Authors: Arto Hellas, Matti Luukkainen
Translators to English: Emilia Hjelm, Alex H. Virtanen, Matti Luukkainen, Virpi Sumu, Birunthan Mohanathas, Etiënne Goossens
Extra material added by: Etiënne Goossens, Maurice Snoeren, Johan Talboom
Adapted for Informatica by: Ruud Hermans

The course is maintained by Technische Informatica Breda


Return values

A method can return a value. In the examples above, methods have not been returning anything. This is expressed by writing void in the first line of the method, just before it’s name.

public static void addThree() {
  ...

When defining a method that returns a value, we also have to define the type of the return value. We can define the type of the return value by writing it just before the name of the method. Next, we have a method that always returns the number 10 (type int). Returning a value is accomplished with the command return:

public static int alwaysReturnTen() {
    return 10;
}

If we want to use the returned value later, we have to catch the return value and store it into a variable:

public static void main(String[] args) {
    int number = alwaysReturnTen();

    System.out.println( "method returned the number " + number );
}

The return value of the method is assigned to a variable of type int just like any other integer. The return value can also be a part of a sentence:

double number = 4 * alwaysReturnTen() + (alwaysReturnTen() / 2) - 8;

System.out.println( "calculation total " + number );

Every variable type we have seen this far can be used as a return value:

public static void methodThatReturnsNothing() {
  // method body
}

public static int methodThatReturnsInteger() {
  // method body, needs a return statement
}

public static String methodThatReturnsText() {
  // method body, needs a return statement
}

public static double methodThatReturnsFloatingpoint() {
  // method body, needs a return statement
}

If the method is defined to have a return value, it also has to return a value. The following method is incorrect:

public static String wrongMethod() {
    System.out.println("I tell you that I will return a String but I do not!");
}

In the following example, we define a method for calculating a sum. Then, we use the method to calculate 2 + 7. The return value (returned after the method call) is assigned to a variable called sumNumbers.

public static int sum(int first, int second) {
    return first + second;
}

Method call:

int sumNumbers = sum(2, 7);
// sumNumbers now holds the value 9
Let us expand the example program so that the user types the numbers.

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    System.out.print("Type the first number: ");
    int first = Integer.parseInt( reader.nextLine() );

    System.out.print("Type the second number: ");
    int second = Integer.parseInt( reader.nextLine() );

    System.out.print("Total: " + sum(first,second) );
}

public static int sum(int first, int second) {
    return first + second;
}

As we can see, the return value of the method does not always need to be assigned to a variable. It can also act as a part of the printing command just like any other integer value.

In the next example, we call the method sum using integers that we get as return values from the method sum.

int first = 3;
int second = 2;

sum(sum(1, 2), sum(first, second));
// 1) the inner methods are executed:
//    sum(1, 2) = 3   and sum(first, second) = 5
// 2) the outer method is executed:
//    sum(3, 5) = 8

The method’s own variables

The following method calculates the average of the numbers the method gets as parameters. The method uses helper variables sum and average. The method’s own variables can be introduced just like any other variables.

public static double average(int number1, int number2, int number3) {

    int sum = number1 + number2 + number3;
    double average = sum / 3.0;

    return average;
}

Exercise method-return-1: Sum of numbers

Create the method sum that calculates the sum of numbers the method receives as parameters.

Place the method in the following program body:

public static int sum(int number1, int number2, int number3, int number4) {
    // write program code here
    // remember that the method needs a return in the end
}

public static void main(String[] args) {
    int answer = sum(4, 3, 6, 1);
    System.out.println("sum: " + answer);
}

Example output:

sum: 14

Note: if an exercise involves a method returning something, it means that the return type needs to be defined for the method, and that the method needs to return a value of that type using the return command. In this case, the method does not print (or use the command System.out.println(..)), the method caller handles printing, here, the main program.

Exercise method-return-2: Least

Create the method least, which returns the least of the numbers given as parameters. If the parameters are equal, you can decide which one is returned.

public static int least(int number1, int number2) {
    // write program code here
    // do not print anything inside the method

    // method needs a return in the end
}

public static void main(String[] args) {
    int answer =  least(2, 7);
    System.out.println("Least: " + answer);
}

Example output:

Least: 2

Exercise method-return-3: Greatest

Create the method greatest, which gets three integers as parameters and then returns the greatest of them. If there are several parameters that are equally great, you can decide which one is returned. Printing should be done in the main program.

public static int greatest(int number1, int number2, int number3) {
    // write your code here
}

public static void main(String[] args) {
    int answer =  greatest(2, 7, 3);
    System.out.println("Greatest: " + answer);
}

Example output:

Greatest: 7

Exercise method-return-4: Average of given numbers

Create the method average, which calculates the average of the numbers it gets as parameters. Inside the method you should use the method sum as a helper!

Place the method in the following program body:

public static double average(int number1, int number2, int number3, int number4) {
    // write your code here
}

public static void main(String[] args) {
    double answer = average(4, 3, 6, 1);
    System.out.println("average: " + answer);
}

Program output:

average: 3.5

Make sure you remember how you can transform a whole number (int) into a decimal number (double)!