5 Static & Documentation

Static Methods and Documentation

Objective

  • Declare and use static methods.
  • Work with setters, getters, overloaded constructors, and static methods.
  • Use the Math class and its static members.
  • Generate documentation using the Javadoc syntax and tool.

Exercise 1*

Geometric Shapes: The Circle

  1. Create a class called Circle.
  2. The class has a field radius, which defaults to 1.0 by the first no argument constructor. The class also has another constructor that instantiates the radius to a given value.
  3. Provide methods that calculate the circumference and the area of the circle using Math.PI and Math.pow().
  4. Provide setRadius() and getRadius() methods. The setRadius() method should verify that radius is greater than or equal to 0.0 and less than 20.0, otherwise it sets radius to 1.0.
  5. Write another class called TestCircle that tests the Circle class.
Circle-radius : double+Circle()+Circle(double)+setRadius(double) : void+getRadius() : double+circumference() : double+area() : double
Solution
.java
 

Exercise 2*

Constructor Overloading

In a Student Admission System, an applicant chooses from among many offered majors such as Computer Science, Computer Engineering, Physics, Mathematics, Industrial Engineering and other majors.

The Major class is represented by the following fields:

  • id: int,
  • title: String,
  • departmentId: int, and
  • totalCreditHours: int.
  1. Write code for the Major class, including the setters, getters, and a fully parameterized constructor.
  2. Add a no-argument constructor that sets id to 999, title to "Unknown", departmentId to 888, and totalCreditHours to 0.
  3. Write a method called display() that outputs the fields of a Major instance, each on a separate line and properly labelled.
  4. Write a class called MajorTest that creates some Major instances and displays their contents using the above method. You should utilize the two overloaded constructors.
Major-id : int-title : String-departmentId : int-totalCreditHours : int+Major()+Major(int, String, int, int)+get*() :type+set*(type) : void+display() : void
Solution
.java
 

Exercise 3

Static Methods

  1. Trace the following method to figure out its task:

    public int digits(int x) {
      double n = 0;
      while (x != 0) {
        x = x / 10;
        n++;
      }
      return n;
    }

    What does the method return?

  2. Does the above code have a compilation error? How can we test it?

  3. Create a new project and a new class IntNumbers then copy the digits() to your class and fix the error.

  4. Your main() method in this class may look as follows:

    public static void main(String arg[]) {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter a value for n: ");
      int n = scanner.nextInt();
      System.out.println(digits(n));
      System.out.println(Math.sqrt(n));
      scanner.close();
    }
  5. Do you have any compilation errors as a result of calling the digits() method? If yes, what is the problem?

  6. Can you explain why did the program not have an error for calling the method Math.sqrt() but it did have a compilation error when calling the method digits()?

    Tip: Explore the Math class in the Java API (opens in a new tab) and read about its sqrt() method.

  7. Add the keyword static after the keyword public and before the keyword int in method digits()’s signature.

    It is concluded that static methods, like the main() method, can only directly call ______ _______.

  8. Does it matter if you put the digits() method before or after the main() method?

  9. How can we define the variable n twice in our program: in the main() and in the digits() methods?

  10. Create a new class called IntNumbersTest, and move the main method from IntNumbers to this new class. Class IntNumbers now only includes digits() method.

    Are we still able to call the method digits() now?

  11. If the method digits() is still static in class IntNumbers, which of the following is the recommended way to call it?

    1. IntNumbers num = new IntNumbers(); System.out.println(num.digits(n));
    2. System.out.println(IntNumbers.digits(n));

    What is the warning message reported by your IDE when you use this technique to access digits()?

  12. It is concluded that there are three ways to call a method:

    1. _____________
    2. _____________
    3. _____________
Solution
.java
 

Exercise 4

Simple GUI Input/Output

Simple dialogs appear in popup windows. Dialogs include short messages or information screens, confirmation boxes, and input prompts for string information. Java’s Swing library uses the JOptionPane class to provide static methods for each type of dialog. Each method has a first parameter that points to a parent, that is, a window that it appears in, or null, which default to the current window.

  • showMessageDialog() has a second parameter for the message to be displayed.

    JOptionPane.showMessageDialog(null, "This is just a message");
  • showInputDialog() has a second parameter for the message to be displayed. Optionally two more parameters can be used to set a dialog title and to select the dialog’s icon. There is both an Ok button and a Cancel button for dialog completion. Any information typed into the entry box is returned as a String.

    String name = JOptionPane.showInputDialog(null, "What's your name:");
  • showConfirmDialog() has a second parameter for the message to be displayed. By default the dialog displays three buttons: Yes, No and Cancel. Optionally two more parameters can be used to set a dialog title and to select the dialog’s icon.

    int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?");

    The JOptionPane.YES_NO_OPTION constant can be used to restrict the displayed buttons to Yes and No only.

    int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?",
                     "App", JOptionPane.YES_NO_OPTION);

    The returned value of type int can be compared to the static constants: YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, etc.

  1. Create a class called Dialogs, and copy the following:

    Dialogs.java
    import javax.swing.JOptionPane;
     
    public class Dialogs {
      public static void main(String[] args) {
        int response;
     
        do {
          // obtain user input (as String) from JOptionPane input Dialogs
          String firstNumber = JOptionPane.showInputDialog("Enter first integer:");
          String secondNumber =
              JOptionPane.showInputDialog("Enter second integer:");
     
          // convert String inputs to int values for use in a calculation
          int integer1 = Integer.parseInt(firstNumber);
          int integer2 = Integer.parseInt(secondNumber);
          int sum = integer1 + integer2;
     
          JOptionPane.showMessageDialog(null, "Sum = " + sum);
          response =
              JOptionPane.showConfirmDialog(null, "Do you want to continue?");
        } while (response == JOptionPane.YES_OPTION);
      }
    }
  2. Run the above application.

  3. The showInputDialog() method returns data of type _______.

  4. To convert a String to an int, we use a method called _______.

  5. Name the static methods and constants used in the above application: _______.

  6. Did you use a class or an instance to access these static methods/constants?

  7. Modify the showConfirmDialog() to display Yes and No buttons only, that is, do not display the Cancel button.

  8. Extend the application to obtain the product, in addition to the sum.

  9. Modify your application such that you define your numbers as double instead of int. Use the static method: Double.parseDouble() instead of Integer.parseInt().

Solution
.java
 

Exercise 5

Working with SecureRandom

In this exercise, we will build an application that helps elementary school students learn multiplication. The application uses simple GUI dialogs, as explained in Exercise 4 above.

  1. Create a new project and then create a new class called RandomApp.

  2. Using class SecureRandom, write a method generateRandom() that returns a random number between 2 and 10.

    Note: Consult the Java API (opens in a new tab) to explore which method of class SecureRandom to use.

  3. Write a method called generateQuestion(), which uses generateRandom() to generate random numbers, then asks the user questions such as: "How much is 6 times 7?"

    The method checks the user’s answer and then returns true if the answer is correct and false otherwise.

  4. Create a new class called RandomTest, which has a main method in which you create an instance of RandomApp, and then use the generateQuestion() method to ask the student a question.

    If the student’s answer is correct, display the message "Well done. Correct answer!", otherwise, display "Sorry. Try again.".

  5. At the end, ask the user if they want to continue. If the choice is Yes, repeat the above, otherwise terminate the loop and stop.

  6. Which methods of RandomApp can be made static?

Solution
.java
 

Exercise 6*

Working with Javadoc

Javadoc is a tool that generates HTML documentation from Javadoc comments (annotations) in the code, similar to the reference pages at https://docs.oracle.com (opens in a new tab); for example the documentation for the SQL module is found at this page (opens in a new tab). In this exercise, we will go over how to write basic Javadoc comments and how to use certain features of Javadoc to generate HTML documentation.

Javadoc Comments

Javadoc recognizes special comments /**...*/ which are highlighted differently than regular comments //... and /*...*/.

Javadoc allows you to attach descriptions to classes, constructors, fields, interfaces, and methods in the generated HTML documentation by placing Javadoc comments directly before their declaration statements.

Your IDE can be used to generate Javadoc comments for your classes/methods by typing /** before a declaration and pressing Enter. Javadoc comments with appropriate tags will be generated, but you still have to write your own descriptions.

  1. Code: Type /** before a declaration and press Enter, or select Javadoc Tools: Generate Javadoc Comments for Open File from the Command Palette, provided by the Javadoc Tools (opens in a new tab) extension.
  2. Eclipse: Select SourceGenerate Element Comment at the corresponding declaration.
  3. IDEA: Type /** before a declaration and press Enter.

Javadoc Tags

Tags are keywords recognized by Javadoc, which define the type of information that follows. Tags come after the description and are separated by a newline.

Here are some common pre-defined tags:

  • @author [author name]: author of a class or interface.
  • @version [version number]: version info of a class or interface.
  • @param [argument name] [argument description]: describes an argument of a method or constructor.
  • @return [description of value]: describes data returned by a method; unnecessary for constructors and void methods.
  • @exception [exception thrown] [exception description]: describes an exception thrown by a method.
  • @throws [exception thrown] [exception description]: same as @exception.

Here is an example using Javadoc comments to describe a class, a field, a constructor, and a method:

Person.java
/**
 * @author Dane Doe 20239999
 * @version 1.0
 */
 
public class Person {
  /**
   * The first name of the person.
   */
  private String firstName;
  /**
   * The last name of the person
   */
  private String lastName;
  /**
   * The age of the person.
   */
  private int age;
 
  /**
   * @param firstName
   *   The first name of the person.
   * @param lastName
   *   The last name of the person.
   * @param age
   *   The age of the person.
   */
  public Person(String firstName, String lastName, int age) {
    setFirstName(firstName);
    setLastName(lastName);
    setAge(age);
  }
 
  public String getFirstName() {
    return firstName;
  }
 
  public void setFirstName(String first) {
    firstName = first;
  }
 
  public String getLastName() {
    return lastName;
  }
 
  public void setLastName(String last) {
    lastName = last;
  }
 
  /**
   * @return The age of the person.
   */
  public int getAge() {
    return age;
  }
 
  /**
   * This method sets the age field for a Person object. It ensures that the
   * <br />
   * argument is positive. If it is negative, the method does nothing.
   * @param years
   *   An integer value that represents the age in years.
   */
  public void setAge(int years) {
    if (years > 0) {
      age = years;
    }
  }
}

To generate the documentation pages using your IDE:

  1. Code: Select Javadoc Tools: Export Javadoc from the Command Palette. You will need to have at least one sub-package defined otherwise the command will fail.
  2. Eclipse: ProjectGenerate Javadoc and follow through with the process.
  3. IDEA: ToolsGenerate JavaDoc.
Solution
.java
 

Exercise 7+

Prime Numbers

  1. Write an application that asks the user to enter an integer number and checks if that number is prime or not.
  2. Modify your application to print all prime numbers between 1 and 100.
  3. Modify your application to count the number of prime numbers between 1 and 1000.
Solution
.java
 

Exercise 8+

Hypotenuse Calculation

Define a method hypotenuse that calculates the hypotenuse, cc, of a right triangle when the lengths of the other two sides, aa and bb, are given using:

c=a2+b2\begin{align*} c &= \sqrt{a^2 + b^2} \end{align*}

The method should take two arguments of type double and return the hypotenuse as a double. Incorporate this method into an application that reads values for aa and bb and performs the calculation with the hypotenuse() method.

Use Math methods pow() and sqrt() to determine the length of the hypotenuse for each of the triangles in the following table:

aabbcc
3.04.0___
5.012.0___
8.015.0___

Note: Class Math also provides a method hypot() to perform this calculation.

Solution
.java
 

Exercise 9+

Geometric Shapes: The Rectangle

Create a class named Rectangle with two data members: length and width and a method to calculate the area which is length * width. The class has three constructors, which are:

  1. Having no parameter: values of both length and width are assigned 0.0.
  2. Having two numbers as parameters: the two numbers are assigned as length and width respectively.
  3. Having one number as parameter: both length and width are assigned that number.
Rectangle-length : double-width : double+Rectangle()+Rectangle(double)+Rectangle(double, double)+area() : double

Now, create a RectangleTestClass and instantiate objects of the Rectangle class having none, one, and two parameters, and print their areas.

Solution
.java
 

Exercise 10+

For this problem, we are going to write a very simple but complete class. The class represents a counter that counts 0, 1, 2, 3, 4, … in sequence. The name of the class is Counter. It has one private instance variable representing the value of the counter and two instance methods:

  • increment() adds 1 to the counter value, and
  • getValue() returns the current counter value.

Write a complete definition for the class Counter.

Counter-counter : long+increment() : void+getValue() : long

The following snippet is meant to simulate tossing a coin 100 times. It should use two Counter objects: headCounter and tailCounter, to count the number of heads and the number of tails. Fill in the blanks so that it will do so:

Counter headCounter, tailCounter;
tailCounter = new Counter();
headCounter = new Counter();
for (int flip = 0; flip < 100; flip++) {
  if (Math.random() < 0.5) { // there is a 50/50 chance that this is true
    // count a "head"
  } else {
    // count a "tail"
  }
}
System.out.println("There were " + + " heads");
System.out.println("There were " + + " tails");
Solution
.java