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
- Create a class called
Circle
. - The class has a field
radius
, which defaults to1.0
by the first no argument constructor. The class also has another constructor that instantiates theradius
to a given value. - Provide methods that calculate the circumference and the area of the circle using
Math.PI
andMath.pow()
. - Provide
setRadius()
andgetRadius()
methods. ThesetRadius()
method should verify thatradius
is greater than or equal to0.0
and less than20.0
, otherwise it setsradius
to1.0
. - Write another class called
TestCircle
that tests theCircle
class.
Solution
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
, andtotalCreditHours
:int
.
- Write code for the
Major
class, including the setters, getters, and a fully parameterized constructor. - Add a no-argument constructor that sets
id
to999
,title
to"Unknown"
,departmentId
to888
, andtotalCreditHours
to0
. - Write a method called
display()
that outputs the fields of aMajor
instance, each on a separate line and properly labelled. - Write a class called
MajorTest
that creates someMajor
instances and displays their contents using the above method. You should utilize the two overloaded constructors.
Solution
Exercise 3
Static Methods
-
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?
-
Does the above code have a compilation error? How can we test it?
-
Create a new project and a new class
IntNumbers
then copy thedigits()
to your class and fix the error. -
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(); }
-
Do you have any compilation errors as a result of calling the
digits()
method? If yes, what is the problem? -
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 methoddigits()
?Tip: Explore the
Math
class in the Java API (opens in a new tab) and read about itssqrt()
method. -
Add the keyword
static
after the keywordpublic
and before the keywordint
in methoddigits()
’s signature.It is concluded that
static
methods, like themain()
method, can only directly call______ _______
. -
Does it matter if you put the
digits()
method before or after themain()
method? -
How can we define the variable
n
twice in our program: in themain()
and in thedigits()
methods? -
Create a new class called
IntNumbersTest
, and move themain
method fromIntNumbers
to this new class. ClassIntNumbers
now only includesdigits()
method.Are we still able to call the method
digits()
now? -
If the method
digits()
is stillstatic
in classIntNumbers
, which of the following is the recommended way to call it?IntNumbers num = new IntNumbers(); System.out.println(num.digits(n));
System.out.println(IntNumbers.digits(n));
What is the warning message reported by your IDE when you use this technique to access
digits()
? -
It is concluded that there are three ways to call a method:
_____________
_____________
_____________
Solution
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 anOk
button and aCancel
button for dialog completion. Any information typed into the entry box is returned as aString
.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
andCancel
. 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 toYes
andNo
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.
-
Create a class called
Dialogs
, and copy the following:Dialogs.javaimport 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); } }
-
Run the above application.
-
The
showInputDialog()
method returns data of type_______
. -
To convert a
String
to anint
, we use a method called_______
. -
Name the static methods and constants used in the above application:
_______
. -
Did you use a class or an instance to access these static methods/constants?
-
Modify the
showConfirmDialog()
to displayYes
andNo
buttons only, that is, do not display theCancel
button. -
Extend the application to obtain the product, in addition to the sum.
-
Modify your application such that you define your numbers as
double
instead ofint
. Use the static method:Double.parseDouble()
instead ofInteger.parseInt()
.
Solution
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.
-
Create a new project and then create a new class called
RandomApp
. -
Using class
SecureRandom
, write a methodgenerateRandom()
that returns a random number between2
and10
.Note: Consult the Java API (opens in a new tab) to explore which method of class
SecureRandom
to use. -
Write a method called
generateQuestion()
, which usesgenerateRandom()
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 andfalse
otherwise. -
Create a new class called
RandomTest
, which has amain
method in which you create an instance ofRandomApp
, and then use thegenerateQuestion()
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."
. -
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. -
Which methods of
RandomApp
can be madestatic
?
Solution
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.
- Code: Type
/**
before a declaration and pressEnter
, or selectJavadoc Tools: Generate Javadoc Comments for Open File
from theCommand Palette
, provided by the Javadoc Tools (opens in a new tab) extension. - Eclipse: Select
Source
→Generate Element Comment
at the corresponding declaration. - IDEA: Type
/**
before a declaration and pressEnter
.
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 andvoid
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:
/**
* @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:
- Code: Select
Javadoc Tools: Export Javadoc
from theCommand Palette
. You will need to have at least one sub-package defined otherwise the command will fail. - Eclipse:
Project
→Generate Javadoc
and follow through with the process. - IDEA:
Tools
→Generate JavaDoc
.
Solution
Exercise 7+
Prime Numbers
- Write an application that asks the user to enter an integer number and checks if that number is prime or not.
- Modify your application to print all prime numbers between 1 and 100.
- Modify your application to count the number of prime numbers between 1 and 1000.
Solution
Exercise 8+
Hypotenuse Calculation
Define a method hypotenuse that calculates the hypotenuse, , of a right triangle when the lengths of the other two sides, and , are given using:
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 and 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:
3.0 | 4.0 | ___ |
5.0 | 12.0 | ___ |
8.0 | 15.0 | ___ |
Note: Class Math
also provides a method hypot()
to perform this calculation.
Solution
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:
- Having no parameter: values of both
length
andwidth
are assigned0.0
. - Having two numbers as parameters: the two numbers are assigned as
length
andwidth
respectively. - Having one number as parameter: both
length
andwidth
are assigned that number.
Now, create a RectangleTestClass
and instantiate objects of the Rectangle
class having none, one, and two parameters, and print their areas.
Solution
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()
adds1
to the counter value, andgetValue()
returns the current counter value.
Write a complete definition for the class Counter
.
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