Last modified: January 07, 2023
The basic math methods in Java look identical to the ones from JavaScript.
Addition: +
Subtraction: -
When you need to plus something by one, instead of "something += 1", you can write "something++" or "++something". Similarly, when you need to subtract something by one, instead of "something -= 1", you can write "something--" or "--something".
Multiplication: *
Division: /
Modulus: %
Be careful about division. Compare these 2 examples below:
public class BeCarefulAboutDivision {
public static void main(String[] args){
double a = 3.0;
double b = 2.0;
System.out.println(a / b);
}
}
public class BeCarefulAboutDivision {
public static void main(String[] args){
int a = 3;
int b = 2;
System.out.println(a / b);
}
}
When we run the first program, 1.5 is printed out. However, when we run the second program, 1 is printed out.
Why the second one printed out 1 instead of 1.5 In Java, a division between two integers must result in integer. Although 3 / 2 should have been 1.5, Java forces it into an integer, and 1.5 became 1.
To make the second program also print out 1.5,
we can convert a
or b
to be doubles so that their division can result in a double:
public class BeCarefulAboutDivision {
public static void main(String[] args){
int a = 3;
int b = 2;
System.out.println((double)a / b);
}
}
This process of converting one data type into another is called typecasting.
In addition to the basic math above, Java also provides several built-in methods for you to perform other convenient math operations, such as:
name | purpose |
---|---|
Math.max(x, y) | returns the greater value between x and y |
Math.min(x, y) | returns the lesser value between x and y |
Math.sqrt(x) | calculates the square root of a number |
Math.abs(x) | calculates the absolute value of a number |
Math.random() | generates a random value between <= 0.0 and < 1.01 |
Watch out the boundary of Math.random(). The generated value could be 0.0, but it could never be 1.0 ↩