Using the Math class

 

Using pre-written Java code

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

Beginning Java programmers will be most interested in the last three of these packages.

import java.util.*;

Notes:

  1. Code import statements at the beginning of the Java source file prior to the class header.

  2. The only package that doesn't require an import statement is java.lang. Its contents are so frequently used that it is automatically available.

  1. 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. 

  1. 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. 

 

The Math class 

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.

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

  1. Which of the following import statements are required in order to use the Math class and its features?

  1. import java.lang.*;

  2. import java.lang.Math

  3. import java.util.*;

  4. import java.util.Math

  5. none of the above

  1. 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));

  1. the statement will not compile

  2. the statement will compile but an error will occur at run time

  3. the statement will compile and run to display "Root = 5.0" on the console

  4. the statement will compile and run to display "Root = -5.0" on the console

  5. the statement will compile and run to display "Root = NaN" on the console

  1. 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);

  1. the first statement will not compile

  2. the second statement will not compile

  3. the statements will compile but an error will occur at run time when the first statement is executed

  4. the statements will compile and run. The message "Result = 8" will be displayed on the console.

  5. the statements will compile and run. The message "Result = 9" will be displayed on the console.

  1. 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
12
public 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");
    }
  }
}
  1. the program will compile and run but the output cannot be determined

  2. the program will compile and run to always display "Biggest number"

  3. the program will compile and run to always display "Smaller number"

  4. the program will compile but an error will occur at run time

  5. a compile error will occur because the Math class was not imported