Java Tutorial » Chapter 8 — Basic Operators

Chapter 8 — Java Basic Operators

Learn about the symbols that perform operations on variables and values.

1. Introduction

What are Operators?

An operator is a symbol that performs a specific operation on one, two, or three operands (variables or values). For example, in `a + b`, the `+` is the operator, and `a` and `b` are the operands.

Java provides a rich set of operators that can be grouped into different categories based on their functionality.

2. Arithmetic Operators

Performing Math

Arithmetic operators are used to perform common mathematical operations like addition, subtraction, etc.

Operator Description Example
+ Addition (also used for String concatenation) a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulo (remainder of division) a % b
public class ArithmeticExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        System.out.println("a + b = " + (a + b)); // 13
        System.out.println("a - b = " + (a - b)); // 7
        System.out.println("a * b = " + (a * b)); // 30
        
        // Integer division truncates the decimal part
        System.out.println("a / b = " + (a / b)); // 3 (not 3.33)

        // Modulo gives the remainder
        System.out.println("a % b = " + (a % b)); // 1 (because 10 = 3*3 + 1)
    }
}
3. Relational Operators

Comparing Values

Relational operators compare two values and always return a boolean result: true or false. They are often used in decision-making statements like `if`.

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
public class RelationalExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        System.out.println("a == b: " + (a == b)); // false
        System.out.println("a != b: " + (a != b)); // true
        System.out.println("a > b: " + (a > b));   // false
        System.out.println("a < b: " + (a < b));   // true
        System.out.println("b >= a: " + (b >= a)); // true
        System.out.println("b <= a: " + (b <= a)); // false
    }
}
4. Bitwise Operators

Operating on Individual Bits

Bitwise operators work directly on the binary representation of integers. They are used for low-level manipulation of bits.

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT (inverts bits)
<< Left Shift
>> Right Shift (sign-propagating)
>>> Right Shift (zero-fill)
public class BitwiseExample {
    public static void main(String[] args) {
        int a = 60;  // binary: 0011 1100
        int b = 13;  // binary: 0000 1101

        int c = a & b; // Bitwise AND -> 0000 1100 (12)
        int d = a | b; // Bitwise OR  -> 0011 1101 (61)
        int e = a ^ b; // Bitwise XOR -> 0011 0001 (49)
        int f = (~a);  // Bitwise NOT -> ...1100 0011 (-61)

        System.out.println("a & b = " + c);
        System.out.println("a | b = " + d);
        System.out.println("a ^ b = " + e);
        System.out.println("~a = " + f);
    }
}
5. Logical Operators

Combining Boolean Conditions

Logical operators are used to combine two or more boolean expressions. They are essential for building complex conditions.

Operator Description
&& Logical AND (true only if both are true)
|| Logical OR (true if at least one is true)
! Logical NOT (inverts boolean value)

Short-Circuiting: The `&&` and `||` operators are "short-circuiting". For `&&`, if the first condition is `false`, the second is not evaluated. For `||`, if the first is `true`, the second is not evaluated. This can improve performance.

public class LogicalExample {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;

        System.out.println("a && b: " + (a && b)); // false
        System.out.println("a || b: " + (a || b)); // true
        System.out.println("!(a && b): " + !(a && b)); // true

        // Example of short-circuiting
        int x = 5;
        // (x > 10) is false, so (x++ > 6) is never evaluated.
        if ((x > 10) && (x++ > 6)) { 
            // this block will not run
        }
        System.out.println("Value of x after short-circuit: " + x); // x is still 5
    }
}
6. Assignment Operators

Assigning and Modifying Values

Assignment operators are used to assign a value to a variable. The most basic is `=`. Others are shorthand for combining an operation with an assignment.

Operator Example Equivalent To
= c = a + b c = a + b
+= c += a c = c + a
-= c -= a c = c - a
*= c *= a c = c * a
/= c /= a c = c / a
%= c %= a c = c % a
public class AssignmentExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 0;

        c = a + b;
        System.out.println("c = a + b -> " + c); // 30

        c += a;
        System.out.println("c += a -> " + c); // 40 (30 + 10)

        c -= b;
        System.out.println("c -= b -> " + c); // 20 (40 - 20)
    }
}
7. Miscellaneous Operators

Other Useful Operators

Java has a few other operators that don't fit neatly into the other categories.

Ternary Operator (?:)

This is a shorthand for a simple `if-else` statement. It's the only operator that takes three operands.

public class TernaryExample {
    public static void main(String[] args) {
        int a = 10;
        int b = (a > 5) ? 100 : 200; // If a > 5, b = 100, else b = 200

        System.out.println("Value of b: " + b); // 100

        String message = (b == 100) ? "a is greater than 5" : "a is not greater than 5";
        System.out.println(message);
    }
}

Increment and Decrement Operators (++, --)

These operators add or subtract 1 from a variable. They can be used in two forms: prefix and postfix.

  • Prefix (++a): Increments `a` first, then returns the new value.
  • Postfix (a++): Returns the original value of `a`, then increments `a`.
public class IncDecExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 10;

        System.out.println(++a); // 11 (a is incremented first)
        System.out.println(a);   // 11

        System.out.println(b++); // 10 (original value is returned first)
        System.out.println(b);   // 11 (b is incremented after)
    }
}
8. Operator Precedence

The Order of Operations

Operator precedence determines the order in which expressions are evaluated. Operators with higher precedence are evaluated first. For example, multiplication has higher precedence than addition, so `2 + 3 * 4` is evaluated as `2 + (3 * 4)`.

You can use parentheses `()` to explicitly define the order of evaluation and make your code more readable.

Precedence Operator
Highest() [] . (Method call, array access, member access)
++ -- ~ ! (Unary operators)
* / % (Multiplication, Division, Modulo)
+ - (Addition, Subtraction)
<< >> >>> instanceof (Shift, Relational)
== != (Equality)
& (Bitwise AND)
^ (Bitwise XOR)
| (Bitwise OR)
&& (Logical AND)
|| (Logical OR)
?: (Ternary)
Lowest= += -= *= /= %= &= |= ^= <<= >>= >>>= (Assignment)