Operators
Java Program to Demonstrate Arithmetic Operators
A Java program to demonstrate the usage of arithmetic operators.
Problem Description
Write a Java program to perform basic arithmetic operations: addition, subtraction, multiplication, division, and modulus.
Code
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}Output
a + b = 15
a - b = 5
a * b = 50
a / b = 2
a % b = 0Explanation
+(Addition): Adds two operands.-(Subtraction): Subtracts the second operand from the first.*(Multiplication): Multiplies two operands./(Division): Divides the numerator by the denominator.%(Modulus): Returns the remainder of the division.
Try Yourself
Practice these variations to master arithmetic operators.
- Remainder: Change
bto 3. What isa % b? - Integer Division: Calculate
5 / 2and print it. Why is it 2 and not 2.5? - Floating Point: Change
ato10.0(double). Now what isa / b? - Order of Operations: Print the result of
5 + 10 * 2. Is it 30 or 25? - Brain Twister: Try to divide by zero (
10 / 0). What happens?
Java program To Calculate Compound Interest
This code takes the principal amount, annual interest rate (as a percentage), number of years, and compounding frequency (how many times per year the interest is compounded) as input from the user.
Java Program to Demonstrate Relational Operators
A Java program to demonstrate the usage of relational operators.
