Print Page Print Page

CH6 – Return Values

  1. Create a new class named ValueMethod and add a new method named countup and a main method.
public class ValueMethod {
  public static void countup(int n){
    if(n==0) {
      System.out.println("Blastoff!");
    } else {
        countup(n-1);
        System.out.println(n);
    }
  }
  public static void main(String[] args){
    ValueMethod.countup(3);
  }
}
  1. Compile the program and run it and you should see the following output.
$ javac ValueMethod.java
$ java ValueMethod
Blastoff!
1
2
3
  1. Add another method named calculateArea and add a call to main. Also comment the call to countup.
public class ValueMethod {
  public static void countup(int n){
    if(n==0) {
      System.out.println("Blastoff!");
    } else {
        countup(n-1);
        System.out.println(n);
    }
  }
  public static double calculateArea(double radius){
    double result = Math.PI * radius * radius;
    return result;
  }
  public static void main(String[] args){
    // ValueMethod.countup(3);
    double answer = ValueMethod.calculateArea(33.22);
    System.out.println(answer);
  }
}
  1. Compile and run the program.
$ javac ValueMethod.java
$ java ValueMethod
3466.962378173842