Using pre-written Java code
The Java compiler makes it easy for programmers to use "packages" of existing code. Most packages contain dozens of related classes with each having a number of useful methods. Among the most frequently used packages are:
Beginning Java programmers will be most interested in the last three of these packages.
Package
Contents
java.applet
Supports Java applets (small programs that may be embedded inside other applications - such as Web pages)
java.awt
The "abstract windows toolkit" supports graphical, Windows programming
java.lang
Supports Java language extensions and mathematical tools
java.text
Supports text formatting and manipulation
java.util
A set of general purpose utility classes
import java.util.*;
Notes:
Code import statements at the beginning of the Java source file prior to the class header.
The only package that doesn't require an import statement is java.lang. Its contents are so frequently used that it is automatically available.
- Optionally, only a selected class within a particular package might be specified, such as
import java.util.TimeZone;
which has features to work with a time zone and determine daylight savings.
- Without an import statement pre-written code can still be accessed, but every time you reference a class or a class feature (such as a method) you would need to use its package name as a qualifier. For example,
java.util.TimeZone.getDefault()
instead of
TimeZone.getDefault()
would be required to retrieve the default time zone of the platform.
Use the help facility to learn about Java packages, their classes, and the features of their classes. In this lesson, we will explore the use of the Math class in the java.lang package.
The Math class
Is part of the java.lang package
Contains class methods for performing basic numeric operations such as random number generation, rounding, absolute value, exponentiation, square root, logarithmic functions, and trigonometric functions
Contains two frequently used public field. These are:
Field
Usage
E
The double value that is closer than any other to e, the base of the natural logarithms
PI
The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter
To display the value of e and the value of pi, you may run the following program:
public class App {
public static void main(String[] args) {
System.out.println("e = " + Math.E);
System.out.println("pi = " + Math.PI);
}
}Note: Because E and PI are fields of the Math class and not methods of the Math class, no parenthesis are coded after their name. Parenthesis are only used to indicate a method call.
Has a number of useful class methods. Among them are the following (with detailed parameter requirements and the returned data type omitted for brevity):
Method
Usage
abs()
Returns the absolute value of a number
ceil()
Returns the smallest (closest to negative infinity) double value that is not less than the argument and is equal to a mathematical integer
cos()
Returns the trigonometric cosine of an angle measured in radians
floor()
Returns the largest (closest to positive infinity) double value that is not greater than the argument and is equal to a mathematical integer
pow()
Returns the value of the first argument raised to the power of the second argument
random()
Returns a double value greater than or equal to 0.0 and less than 1.0
round()
Rounds a real number to the nearest integer value
sin()
Returns the trigonometric sine of an angle measured in radians
sqrt()
Returns the correctly rounded positive square root of a double value
toDegrees()
Converts an angle measured in radians to the equivalent angle measured in degrees
toRadians()
Converts an angle measured in degrees to the equivalent angle measured in radians
Some of the above methods are "overloaded" to accept different parameter types. Overloading will be covered in a later lesson.
Consult the help facility of your Java development environment or the Java API for more details.
Sample programs
The following small samples will help you understand how easy it is to use the class methods of the Math class:
Example 1: Performing some miscellaneous mathematical calculations on a number
public class App {
public static void main(String[] args) {
double x;
char again;
do {
Utility.separator(50, '~');
System.out.print("Enter a number: ");
x = Keyboard.readDouble();
Utility.skip();
System.out.println("\tCeiling = " + Math.ceil(x));
System.out.println("\tFloor = " + Math.floor(x));
System.out.println("\tRounded = " + Math.round(x));
System.out.println("\tSquared = " + Math.pow(x, 2));
System.out.println("\tSquare root = " + Math.sqrt(x));
Utility.skip();
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
} while (again == 'Y' || again == 'y');
}
}Note: Try several different values when testing this program to see what the various methods do (including a negative number).
Example 2: Simulating 100 rolls of a single die to generate an integer value from 1 to 6
public class App {
public static void main(String[] args) {
int value;
for (int i = 1; i <= 100; i++) {
value = (int) (((Math.random() * 1000) % 6) + 1);
System.out.println("Roll " + i + ": " + value);
}
}
}Note: The random() method returns a double that is less than 1.0 and greater than or equal to zero. Multiplying by 1000 provides extra digits on the left of the decimal point so that modulo 6 can produce a fairly random value from 0 to 5. By adding 1 and casting to an int, the die's value can be stored in an int variable.
Example 3: Calculating the area of a circle
public class App {
public static void main(String[] args) {
double radius;
double area;
char again;
do {
Utility.separator(50, '~');
System.out.print("Enter the radius: ");
radius = Keyboard.readDouble();
Utility.skip();
if (radius <= 0) {
System.out.println("\tInvalid radius");
}
else {
area = Math.PI * Math.pow(radius, 2);
System.out.println("\tArea = " + area);
}
Utility.skip();
System.out.print("Again? (Y/N): ");
again = Keyboard.readChar();
} while (again == 'Y' || again == 'y');
}
}Note: The Math.pow() method is used to square the radius of the circle.
Lab exercise for Ferris students
E-mail your answers to this assignment no later than the due date listed in the class schedule.
Review questions
Which of the following import statements are required in order to use the Math class and its features?
import java.lang.*;
import java.lang.Math
import java.util.*;
import java.util.Math
none of the above
If someNumber is a short variable with a value of -25, which one of the answers below is true of attempting to compile and execute the following statement?
System.out.println("Root = " + Math.sqrt(someNumber));
the statement will not compile
the statement will compile but an error will occur at run time
the statement will compile and run to display "Root = 5.0" on the console
the statement will compile and run to display "Root = -5.0" on the console
the statement will compile and run to display "Root = NaN" on the console
Assuming all unseen code is correct, what will happen when an attempt is made to compile and execute the following statements?
int y = Math.pow(2, 3);
System.out.println("Result = " + y);
the first statement will not compile
the second statement will not compile
the statements will compile but an error will occur at run time when the first statement is executed
the statements will compile and run. The message "Result = 8" will be displayed on the console.
the statements will compile and run. The message "Result = 9" will be displayed on the console.
Which one statement is true about the application shown below? The line numbers are for reference purposes only.
1
2
3
4
5
6
7
8
9
10
11
12public class App {
public static void main(String[] args) {
double x = Math.random();
double y = Math.ceil(x);
if (x == y) {
System.out.println("Biggest number");
}
else {
System.out.println("Smaller number");
}
}
}
the program will compile and run but the output cannot be determined
the program will compile and run to always display "Biggest number"
the program will compile and run to always display "Smaller number"
the program will compile but an error will occur at run time
a compile error will occur because the Math class was not imported