Java Tutorial 0/145 lessons ~6 min read Lesson 10

    Operators

    java operators arithmetic assignment relational logical ternary bitwise shift precedence increment decrement equals comparison

    Course progress0%
    Focus
    23 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Almost every Java program performs operations on data.

    A banking application calculates account balances.

    An e-commerce website calculates discounts.

    A school management system compares student marks.

    A login system verifies usernames and passwords.

    A game updates scores and player positions.

    These operations are performed using operators.

    An operator is a symbol that tells Java to perform a specific operation on one or more values (called operands).

    Example:

    java
    int total = 10 + 20;

    Here:

    • 10 and 20 are operands
    • + is the operator

    Operators are one of the most frequently used features in Java and are essential for writing logical, mathematical, and business-related programs.

    In this lesson, you'll learn:

    • Arithmetic Operators
    • Assignment Operators
    • Comparison (Relational) Operators
    • Logical Operators
    • Unary Operators
    • Increment & Decrement Operators
    • Ternary Operator
    • Bitwise Operators
    • Shift Operators
    • Operator Precedence
    • Real-world examples
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions

    Types of Operators

    Java provides several categories of operators.

    Java Operators
    ├── Arithmetic
    ├── Assignment
    ├── Relational
    ├── Logical
    ├── Unary
    ├── Increment & Decrement
    ├── Ternary
    ├── Bitwise
    └── Shift

    Let's explore each category.

    Arithmetic Operators

    Arithmetic operators perform mathematical calculations.

    OperatorMeaningExample
    +Addition5 + 3
    -Subtraction5 - 3
    *Multiplication5 * 3
    /Division10 / 2
    %Modulus (Remainder)10 % 3

    Example:

    java
    int a = 20;
    int b = 6;
    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);

    Output:

    26
    14
    120
    3
    2

    Real-World Example: Shopping Total

    An online shopping application calculates the total price.

    java
    double price = 1200.00;
    double tax = 216.00;
    double total = price + tax;
    System.out.println(total);

    Output:

    1416.0

    Assignment Operators

    Assignment operators assign values to variables.

    Basic assignment:

    java
    int age = 25;

    Compound assignment operators:

    OperatorExampleEquivalent
    +=x += 5x = x + 5
    -=x -= 5x = x - 5
    *=x *= 5x = x * 5
    /=x /= 5x = x / 5
    %=x %= 5x = x % 5

    Example:

    java
    int score = 80;
    score += 10;
    System.out.println(score);

    Output:

    90

    Relational (Comparison) Operators

    These operators compare values and always return a boolean.

    OperatorMeaning
    ==Equal to
    !=Not equal to
    >Greater than
    <Less than
    >=Greater than or equal
    <=Less than or equal

    Example:

    java
    int age = 18;
    System.out.println(age >= 18);

    Output:

    true

    Real-World Example: Voting Eligibility

    Determine voting eligibility.

    java
    int age = 20;
    boolean canVote = age >= 18;
    System.out.println(canVote);

    Output:

    true

    Logical Operators

    Logical operators combine multiple conditions.

    OperatorMeaning
    &&Logical AND
    ||Logical OR
    !Logical NOT

    Logical AND (`&&`)

    Both conditions must be true.

    java
    int age = 25;
    boolean citizen = true;
    System.out.println(age >= 18 && citizen);

    Output:

    true

    Logical OR (`||`)

    Only one condition must be true.

    java
    boolean weekend = false;
    boolean holiday = true;
    System.out.println(weekend || holiday);

    Output:

    true

    Logical NOT (`!`)

    Reverses a boolean value.

    java
    boolean loggedIn = false;
    System.out.println(!loggedIn);

    Output:

    true

    Unary Operators

    Unary operators work with a single operand.

    OperatorMeaning
    +Unary plus
    -Unary minus
    !Logical NOT
    ++Increment
    --Decrement

    Example:

    java
    int number = 10;
    System.out.println(-number);

    Output:

    -10

    Increment Operator (`++`)

    Increases a value by one.

    java
    int count = 5;
    count++;
    System.out.println(count);

    Output:

    6

    Decrement Operator (`--`)

    Decreases a value by one.

    java
    int count = 5;
    count--;
    System.out.println(count);

    Output:

    4

    Prefix vs Postfix

    Prefix:

    java
    int x = 5;
    System.out.println(++x);

    Output:

    6

    Postfix:

    java
    int x = 5;
    System.out.println(x++);
    System.out.println(x);

    Output:

    5
    6

    Rule:

    • Prefix updates the value before it is used.
    • Postfix uses the current value first, then updates it.

    Ternary Operator

    The ternary operator is a compact alternative to a simple if-else statement.

    Syntax:

    java
    condition ? valueIfTrue : valueIfFalse

    Example:

    java
    int age = 20;
    String result = age >= 18 ? "Adult" : "Minor";
    System.out.println(result);

    Output:

    Adult

    Bitwise Operators

    Bitwise operators work directly with the binary representation of integers.

    OperatorMeaning
    &Bitwise AND
    |Bitwise OR
    ^Bitwise XOR
    ~Bitwise Complement

    Example:

    java
    int a = 5;
    int b = 3;
    System.out.println(a & b);

    These operators are commonly used in low-level programming, networking, cryptography, and performance-sensitive applications.

    Shift Operators

    Shift operators move bits left or right.

    OperatorMeaning
    <<Left Shift
    >>Signed Right Shift
    >>>Unsigned Right Shift

    Example:

    java
    int value = 8;
    System.out.println(value << 1);

    Output:

    16

    Shifting left by one position is generally equivalent to multiplying by two for positive integers.

    Operator Precedence

    Java evaluates expressions according to operator precedence.

    Example:

    java
    int result = 10 + 5 * 2;

    Output:

    20

    Multiplication is performed before addition.

    Use parentheses to make expressions clear.

    java
    int result = (10 + 5) * 2;

    Output:

    30

    Real-World Example: Premium Discount

    An online shopping application applies a discount only if the customer is a premium member and the order value exceeds ₹5,000.

    java
    double orderAmount = 6500;
    boolean premiumMember = true;
    boolean eligibleForDiscount =
    orderAmount > 5000 && premiumMember;
    System.out.println(eligibleForDiscount);

    Output:

    true

    Best Practices

    Use Parentheses for Clarity

    Even if operator precedence makes an expression valid, parentheses improve readability.

    Example:

    java
    double total = (price + tax) - discount;

    Prefer Readability

    Avoid writing overly complex expressions in a single line.

    Break them into smaller steps if needed.

    Use Compound Assignment Carefully

    += and similar operators improve readability for simple updates.

    Avoid chaining assignments when it makes the code confusing.

    Avoid Magic Numbers

    Instead of:

    java
    salary = salary * 12;

    Use descriptive constants where appropriate.

    Compare Objects Correctly

    For primitive values, use ==.

    For many objects such as String, compare contents using methods like .equals() instead of ==. You'll learn this in the Strings lesson.

    Common Mistakes

    Using = Instead of ==

    Incorrect:

    java
    if (age = 18)

    Correct:

    java
    if (age == 18)

    = assigns a value.

    == compares values.

    Integer Division

    java
    System.out.println(5 / 2);

    Output:

    2

    Because both operands are integers, the fractional part is discarded.

    Use a floating-point operand if you need a decimal result.

    Confusing Prefix and Postfix

    java
    x++;

    is not the same as

    java
    ++x;

    Understand when the increment happens.

    Ignoring Operator Precedence

    Always use parentheses if there's any possibility of confusion.

    Comparing Strings with ==

    == checks whether two references point to the same object, not whether two strings contain the same text.

    Use .equals() for content comparison.

    Hands-on Exercise

    Create a Java program that:

    1. Calculates the total bill using arithmetic operators.
    2. Updates a score using assignment operators.
    3. Checks whether a student passed using relational operators.
    4. Determines eligibility for a scholarship using logical operators.
    5. Demonstrates prefix and postfix increment.
    6. Uses the ternary operator to display "Pass" or "Fail".
    7. Uses a left shift operator on an integer and explains the result.
    8. Uses parentheses to change the outcome of an arithmetic expression.

    Try predicting the output before running each example.

    Summary

    Operators are the building blocks of Java expressions.

    They allow you to perform calculations, compare values, evaluate conditions, manipulate bits, and control program logic.

    Understanding how operators work—and especially how precedence and data types affect expressions—will help you write correct, readable, and efficient Java programs.

    Key Takeaways

    • Operators perform operations on one or more operands.
    • Java provides arithmetic, assignment, relational, logical, unary, ternary, bitwise, and shift operators.
    • Comparison operators return boolean values.
    • Prefix and postfix increment behave differently.
    • Use parentheses to improve readability and avoid precedence-related bugs.
    • Integer division discards the fractional part.
    • Use == for primitive comparisons and appropriate methods such as .equals() for comparing object contents.

    Professional Interview Questions

    1What is the difference between = and == in Java?

    Professional Answer

    The = operator assigns a value to a variable, whereas the == operator compares two values. For primitive types, == compares actual values. For object references, == checks whether both references point to the same object.

    Follow-up Questions

    • How do you compare two String objects?
    • Why does == behave differently for primitives and objects?

    Interview Tip: Clearly distinguish assignment from comparison, then explain the difference between primitive values and object references.

    2What is the difference between prefix (++x) and postfix (x++) increment?

    Professional Answer

    With prefix increment (++x), the variable is incremented before its value is used. With postfix increment (x++), the current value is used first, and the increment happens afterward.

    Follow-up Questions

    • What will System.out.println(x++) print if x is 5?
    • When would prefix increment be preferable?

    Interview Tip: Walk through a simple example step by step instead of only giving the definition.

    3Why does 5 / 2 return 2 instead of 2.5?

    Professional Answer

    Both operands are integers, so Java performs integer division, which discards the fractional part. To obtain a decimal result, at least one operand must be a floating-point type, for example 5.0 / 2.

    Follow-up Questions

    • What is the result of 5.0 / 2?
    • How does Java choose the result type in arithmetic expressions?

    Interview Tip: Mention that Java performs automatic numeric promotion during arithmetic operations, but the operand types determine the kind of division performed.

    Ready to mark this lesson complete?Track your journey across the entire course.