JAVA Tutorial

Java Math


Numerous methods in the Java Math class let you work with numbers to solve mathematical problems.


Math.max(x,y)

The greatest value of x and y can be found using the Math.max(x,y) method:

Example

				
					Math.max(5, 10);
				
			

Math.min(x,y)

The lowest value of x and y can be found using the Math.min(x,y) method:

Example

				
					Math.min(5, 10);
				
			

Math.sqrt(x)

The square root of x is returned by the Math.sqrt(x) function:

Example

				
					Math.sqrt(64);
				
			

Math.abs(x)

The procedure Math.abs(x) yields the value of x in absolute (positive) terms:

Example

				
					Math.abs(-4.7);
				
			

Random Numbers

A random number between 0.0 (inclusive) and 1.0 (exclusive) is returned by Math.random():

Example

				
					Math.random();
				
			

If you want more control over the random number, you can use the following formula, for instance, if you just want a random number between 0 and 100:

Example

				
					int randomNum = (int)(Math.random() * 101);  // 0 to 100
				
			
Share this Doc

Java Math

Or copy link

Explore Topic