CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
Working with data types
Math class

The Math class

java.lang.Math

Common static methods of the Math class

Method Returns
round(float or double) The closest long value to a double value or the closest int value to a float value. The result has no decimal places.
pow(number, power) A double value of a double argument (number) that is raised to the power of another double argument (power).
sqrt(number) A double value that's the square root of the double argument.
max(a, b) The greater of two float, double, int, or long arguments.
min(a, b) The lesser of two float, double, int, or long arguments.
random() A random double value greater than or equal to 0.0 and less than 1.0.

Math class examples

The round method

long result = Math.round(1.667); // result is 2
int result = Math.round(1.49F); // result is 1

The pow method

double result = Math.pow(2, 2); // result is 4.0 (2*2)
double result = Math.pow(2, 3); // result is 8.0 (2*2*2)
double result = Math.pow(5, 2); // result is 25.0 (5 squared)
int result = (int) Math.pow(5, 2); // result is 25 (5 squared)

The sqrt method

double result = Math.sqrt(20.25); // result is 4.5

The max and min methods

int x = 67;
int y = 23;
int max = Math.max(x, y); // max is 67
int min = Math.min(x, y); // min is 23

The random method

double x = Math.random() * 100; // result is a value >= 0.0 and < 100.0
long result = (long) x; // converts the result from double to long

Code that generates a random number.

public class SomeRandomNumbers
{
   public static void main (String[] args)
   {
	  // random number 0.0 up to but not including 1.0
      double ran = Math.random();
      System.out.println(ran);
      // between 1 and 10
      int ran1 = 1 + (int) (Math.random()*10);
      System.out.println(ran1);
      // between 1 and 13
      int ranCard = ((int) (Math.random()*100)%13+1);
      System.out.println(ranCard);
   }
}
The console after the program finishes

Previous | NumberFormat class | Math class | Integer and Double classs | Next