the Math class
•Java provides certain math functions for us. The Math class contains methods and constants that can be very useful.
•The Math class is like the String class; it is used so often that it is automatically imported.
AP methods in Math classMethod Return type Returns
Math.sqrt(x) double square root of x (>=0)
Math.pow(x,y) double xy
Math.abs(x) double or int absolute value of x
Math.random() double returns a random value >= 0 and < 1
Useful variables in Math class
Math.PI double gives a close approx to pi
OTHERS ARE FOUND AT THE API HERE
Static methods
• The Math class contains static methods and static fields.
• This means that the method does not operate on a particular object.
• You do not instantiate an object of the Math class in order to use the methods of the Math class.
• You invoke the square root method by– Math.sqrt(4)
Examplepublic static void main(String[] args) {
System.out.println(Math.sqrt(16));System.out.println(Math.random());System.out.println((int)(Math.random()*3+1));System.out.println(Math.abs(-5.1));
System.out.println(Math.abs(-5));System.out.println(Math.pow(2,5));
}4.00.787215267182144215.1532.0
Examplepublic class Circle{
// Other code goes here
// Returns the circumference of the Circlepublic double findCircumference(){ return Math.PI * diameter; }
// Returns the area of the Circlepublic double findArea(){ double radius = diamter/2; return Math.PI * Math.pow(radius,2);
}
}
Math.random()The method Math.random() is really useful. Recall it returns a double from 0.0 to 1.0 (but not including 1.0)
So values we might get could be:
•.342519638...
•.00043242...
•.956832443...
A clever way to find a random integer between 0 and 5 inclusive we could multiply by 6 and find the integer value of that number.
• int randomFrom0To5= (int)(Math.random()*6);
If we wanted a random value from 1 to 52, we could do much the same, multiply by 52 (this would give us values from 0 to 51.9999. If we took the (int) of that we would get values from 0 to 51. We then would have to add 1 to that.
• int randomFrom1To52= (int)(Math.random()*52) + 1;