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.
Math Absolute
Math.abs(- a)
With the help of this method, we can find positive value of any given negative numbers.
Math Round
Math.round(a)
With the help of this method, we can round up any floating numbers.
Math Random
Math.random()
With the help of this method, we can generate random number between 0 and 1.
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:
Here is an example:
Math Square Root
Math.sqrt(a)
With the help of this method, we can find square root of any number we want..
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:
Output:
String in Java Previous Next Taking Input in Java
