Math in Java

Same as String, Math is also a class in Java. We can do bunch of things with this class and it's methods. As the word says, This class is used to do operation with mathematical expression and problems. Some examples are finding square root, power, absolute value and many more.


Math Min and Max

Math.max(a, b) and Math.min(a, b)
With the help of this method, we can find maximum or minimum number from given numbers.

System.out.println(Math.min(50, 10)); System.out.println(Math.max(50, 10));
It will print 10 and 50 as output.


Math Absolute

Math.abs(- a)
With the help of this method, we can find positive value of any given negative numbers.

System.out.println(Math.abs(-10.23));
It will print 10.23 as output.


Math Round

Math.round(a)
With the help of this method, we can round up any floating numbers.

System.out.println(Math.round(10.23));
It will print 10 as output.


Math Random

Math.random()
With the help of this method, we can generate random number between 0 and 1.

System.out.println(Math.random());
It will print any value between 0 and 1 as output.

Lets be tricky here. What if you want to generate random number between range you want? Well, Java does not have that method but we can do some tricks. Math.random() * (high - low) + low Take a look:

double MyRan = Math.random() * (20 - 10) + 10; System.out.println(MyRan);
Now it will give us random value between 10 to 20. You still get floating numbers, right? But hey, we just learned rounding values few seconds ago. We can use that.
Here is an example:
double MyRan = Math.random() * (20 - 10) + 10; long myVal = Math.round(MyRan); System.out.println(myVal)
There you go. Now you can get random number between any range you want.


Math Square Root

Math.sqrt(a)
With the help of this method, we can find square root of any number we want..

System.out.println(Math.sqrt(64));
It will print 8.0 as output.


You can see different data types for different methods above. They are because that method return value of that data type. These are some basic Math methods. We have many more Math methods in java.
Click here to read them in details with data return type.


Test it yourself

Code:

public class JavaMath { public static void main(String[] args) { int a = 10; int b = 50; int c = -23; double d = 10.23; int e = 64; System.out.println(Math.max(a, b)); System.out.println(Math.min(a, b)); System.out.println(Math.abs(c)); System.out.println(Math.round(d)); System.out.println(Math.sqrt(e)); //generate random number between 10 to 20 long myRan = Math.round( Math.random() * (20 - 10) + 10); System.out.println(myRan); } }

Output:

50
10
23
10
8.0
19


String in Java Previous Next Taking Input in Java