Java Operators

Learn about arithmetic, assignment, comparison, and logical operators in Java.

Quick Summary

  • Operators are symbols that perform actions on variables and values.
  • Java includes arithmetic, relational, logical, assignment, increment/decrement, and ternary operators.
  • Each operator returns a value and helps build logic in Java programs.

1. Arithmetic Operators

Used for mathematical calculations.

Try example:

public class ArithmeticDemo {
    public static void main(String[] args) {

        int a = 20;
        int b = 6;

        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));
    }
}

2. Relational (Comparison) Operators

Used to compare two values. Returns true or false.

Try example:

public class RelationalDemo {
    public static void main(String[] args) {

        int x = 15;
        int y = 20;

        System.out.println(x == y);
        System.out.println(x != y);
        System.out.println(x > y);
        System.out.println(x < y);
        System.out.println(x >= y);
        System.out.println(x <= y);
    }
}

3. Logical Operators

Used to combine or invert boolean expressions.

Try example:

public class LogicalDemo {
    public static void main(String[] args) {

        boolean isVerified = true;
        boolean isAdmin = false;

        System.out.println(isVerified && isAdmin);
        System.out.println(isVerified || isAdmin);
        System.out.println(!isVerified);
    }
}

4. Assignment Operators

Used to assign values to variables with additional operations.

Try example:

public class AssignmentDemo {
    public static void main(String[] args) {

        int n = 10;

        n += 5;
        System.out.println(n);

        n -= 3;
        System.out.println(n);

        n *= 2;
        System.out.println(n);

        n /= 4;
        System.out.println(n);
    }
}

5. Increment & Decrement Operators

Try example:

public class IncrementDecrementDemo {
    public static void main(String[] args) {

        int value = 10;

        System.out.println(value++); // post-increment
        System.out.println(++value); // pre-increment

        System.out.println(value--); // post-decrement
        System.out.println(--value); // pre-decrement
    }
}

6. Ternary Operator

A compact alternative to if-else.

Try example:

public class TernaryDemo {
    public static void main(String[] args) {

        int hour = 14;

        String message = (hour < 18)
                ? "Good day from VINAR TECH"
                : "Good evening from VINAR TECH";

        System.out.println(message);
    }
}
Sidebar Ad Space
Advertisement Space