Core Java Fundamentals ยท Operators
Learn the fundamental arithmetic operators in Java to perform mathematical calculations like addition, subtraction, multiplication, division, and finding remainders.
public class ArithmeticDemo {
public static void main(String[] args) {
// Declare and initialize two integer variables
int a = 20;
int b = 7;
// 1. Addition (+)
int sum = a + b;
System.out.println("Sum: " + sum);
// 2. Subtraction (-)
int difference = a - b;
System.out.println("Difference: " + difference);
// 3. Multiplication (*)
int product = a * b;
System.out.println("Product: " + product);
// 4. Integer Division (/)
int quotient = a / b;
System.out.println("Integer Quotient: " + quotient);
// 5. Floating-Point Division
double preciseQuotient = (double) a / b;
System.out.println("Precise Quotient: " + preciseQuotient);
// 6. Modulus (%) - Remainder of a division
int remainder = a % b;
System.out.println("Remainder: " + remainder);
}
}a and assign it the value 20. This value is stored in memory.b and assign it the value 7.+ adds the values of a and b (20 + 7). The result, 27, is stored in a new variable sum.sum.- subtracts b from a (20 - 7). The result, 13, is stored in difference.* multiplies a and b (20 * 7). The result, 140, is stored in product./ performs integer division when both operands are integers. 20 / 7 is 2.857..., but since it is integer division, the decimal part is truncated. The result is 2.double. (double) a temporarily treats a as 20.0. Now, the division is 20.0 / 7, which results in a double value.% gives the remainder of a division. 20 divided by 7 is 2 with a remainder of 6. This operator is very useful for tasks like checking for even or odd numbers.