Post

Operators and Expressions

In Java, **operators** are special symbols used to perform operations on variables and values. An **expression** is a combination of variables, operators, and values that produces a result.

Operators and Expressions

1. Arithmetic Operators

Used for basic math operations.

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b

2. Relational / Comparison Operators

Used to compare values.

OperatorDescriptionExampleResult
==Equal toa == btrue/false
!=Not equal toa != btrue/false
>Greater thana > btrue/false
<Less thana < btrue/false
>=Greater or equala >= btrue/false
<=Less or equala <= btrue/false

3. Logical Operators

Used to combine multiple conditions.

OperatorDescriptionExample
&&Logical ANDa > 0 && b < 10
\|\|Logical ORa > 0 \|\| b < 10
!Logical NOT!(a > 0)

4. Assignment Operators

Used to assign values.

OperatorExampleEquivalent
=a = bassign b to a
+=a += ba = a + b
-=a -= ba = a - b
*=a *= ba = a * b
/=a /= ba = a / b
%=a %= ba = a % b

🔹 5. Unary Operators Operate on a single operand.

OperatorDescriptionExample
+Unary plus+a
-Unary minus-a
++Incrementa++ or ++a
--Decrementa-- or --a
!Logical NOT!true

6. Ternary Operator (? Operator)

A shorthand for if-else.

1
int max = (a > b) ? a : b;

Code Demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class OperatorDemo {
    public static void main(String[] args) {
        int a = 10, b = 3;

        // Arithmetic
        System.out.println("Sum: " + (a + b));
        System.out.println("Remainder: " + (a % b));

        // Comparison
        System.out.println("a > b? " + (a > b));

        // Logical
        boolean result = (a > 5) && (b < 5);
        System.out.println("Logical AND: " + result);

        // Assignment
        int c = 5;
        c += 3; // same as c = c + 3
        System.out.println("After += : " + c);

        // Ternary
        int max = (a > b) ? a : b;
        System.out.println("Max: " + max);
    }
}

Output:

1
2
3
4
5
6
Sum: 13
Remainder: 1
a > b? true
Logical AND: true
After += : 8
Max: 10
This post is licensed under CC BY 4.0 by the author.