Computer Science Researcher • Educator • Programming Instructor
Operators allow you to perform actions on variables and values. Java provides several types of operators, such as:
These operators perform basic mathematical calculations.
| Operator | Description |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus (remainder) |
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 3;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
| Operator | Meaning |
|---|---|
| = | Assign value |
| += | Add then assign |
| -= | Subtract then assign |
| *= | Multiply then assign |
| /= | Divide then assign |
public class Main {
public static void main(String[] args) {
int x = 10;
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2; // x = x * 2
x /= 4; // x = x / 4
System.out.println("Final value: " + x);
}
}
Used to compare two values. Result is true or false.
| Operator | Description |
|---|---|
| == | Equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater or equal |
| <= | Less or equal |
public class Main {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}
}
| Operator | Description |
|---|---|
| && | Logical AND |
| || | Logical OR |
| ! | Logical NOT |
public class Main {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a); // false
}
}
Increase or decrease value by 1.
| Operator | Meaning |
|---|---|
| ++ | Increment |
| -- | Decrement |
public class Main {
public static void main(String[] args) {
int x = 5;
x++; // 6
x--; // 5
System.out.println("Final value: " + x);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter first number: ");
double a = input.nextDouble();
System.out.print("Enter second number: ");
double b = input.nextDouble();
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
}
}