Operators — Arithmetic, Comparison, Logical, Bitwise

অপারেটর — গণিত, তুলনা, যুক্তি, বিট

Read: ~30 min Intermediate 5 practice problems Live code runner

1. Operators — Building Expressions

Operators combine values into expressions that produce new values. Java has four main families: arithmetic, comparison, logical, and bitwise. A handful of subtleties — integer division, short-circuit, casting — trip up every beginner at least once.

Operator দিয়ে মান একত্রিত করে expression তৈরি হয়, যা থেকে নতুন মান পাওয়া যায়। Java-তে চারটি পরিবার — arithmetic, comparison, logical, bitwise। integer division, short-circuit ও casting-এ সাবধান থাকতে হবে।

2. Arithmetic — and the Integer Division Trap

Main.java
class Main {
    public static void main(String[] args) {
        System.out.println(7 + 3);       // 10
        System.out.println(7 - 3);       // 4
        System.out.println(7 * 3);       // 21
        System.out.println(7 / 3);       // 2  ← INTEGER division
        System.out.println(7 % 3);       // 1  ← remainder

        System.out.println(7.0 / 3);     // 2.333... ← one float operand
        System.out.println((double)7 / 3); // same, via cast

        int x = 5;
        x += 3;   // compound assignment
        x *= 2;
        System.out.println(x); // 16
        System.out.println(x++); // 16 (post-increment)
        System.out.println(++x); // 18 (pre-increment)
    }
}
Integer division rule: if both operands are integers, / truncates toward zero. To get a decimal result, at least one operand must be a floating type, or you must cast.
দুটি int ভাগ করলে ভগ্নাংশ হারিয়ে যায় (7 / 3 == 2)। দশমিক ফলাফল চাইলে একটি operand-কে double করতে হবে (7.0 / 3, অথবা (double) 7 / 3)। % ভাগশেষ। ++x আগে বাড়ায়, x++ পরে।

3. Comparison — ==, !=, <, >

Comparison operators produce boolean. For primitives, == compares values; for objects, it compares references. Use .equals() for object value comparison.

Main.java
class Main {
    public static void main(String[] args) {
        System.out.println(5 == 5);     // true
        System.out.println(5 != 3);     // true
        System.out.println(5 >= 5);     // true

        String a = "hello";
        String b = new String("hello");
        System.out.println(a == b);         // false — different objects
        System.out.println(a.equals(b));    // true  — same chars
    }
}
Primitive-এ == মান মেলায়। Object-এ == reference মেলায় — দুটি different object হলেও একই content থাকতে পারে। তাই String ও অন্য object মেলাতে সবসময় .equals() ব্যবহার করুন।

4. Logical Operators & Short-Circuit Evaluation

&&, ||, and ! work on booleans. The first two short-circuit: the right operand is skipped if the result is already determined.

Main.java
class Main {
    static boolean loud(boolean v, String tag) {
        System.out.println("  evaluated " + tag);
        return v;
    }
    public static void main(String[] args) {
        System.out.println("AND short-circuit:");
        System.out.println(loud(false, "A") && loud(true, "B")); // B skipped

        System.out.println("OR short-circuit:");
        System.out.println(loud(true, "A") || loud(false, "B"));  // B skipped

        System.out.println("NOT: " + !(5 > 3));   // false
    }
}
Short-circuit-এর সুবিধা — if (x != null && x.size() > 0) নিরাপদ; x null হলে size() call-ই হয় না, NPE থেকে বাঁচি।

5. Bitwise — Fast Tricks on Integer Bits

OpMeaningExample (8-bit)
&AND each bit0b1100 & 0b1010 = 0b1000
|OR each bit0b1100 | 0b1010 = 0b1110
^XOR each bit0b1100 ^ 0b1010 = 0b0110
~NOT — flip all bits~0b0000_0001 = 0b1111_1110
<<Left shift1 << 3 = 8
>>Arithmetic right shift (sign extend)-8 >> 1 = -4
>>>Logical right shift (zero fill)-1 >>> 28 = 15
Main.java
class Main {
    public static void main(String[] args) {
        int a = 0b1100, b = 0b1010;
        System.out.println(Integer.toBinaryString(a & b));  // 1000
        System.out.println(Integer.toBinaryString(a | b));  // 1110
        System.out.println(Integer.toBinaryString(a ^ b));  // 0110

        System.out.println(1 << 3);         // 8  (multiply by 2^n)
        System.out.println(32 >> 2);        // 8  (divide by 2^n)

        // Odd/even trick
        int n = 17;
        System.out.println((n & 1) == 0 ? "even" : "odd");
    }
}
Bitwise operator দ্রুত এবং নিচুস্তরের কাজে দারুণ — bit flag, optimization, hash function-এ কাজে লাগে। n & 1 দিয়ে সহজেই odd/even বলা যায়। << মানে 2-র গুণফল, >> মানে 2-র ভাগ।

6. Precedence & Casting

Operators have priority levels. * binds tighter than +, and && binds tighter than ||. When in doubt, use parentheses — readability always wins.

Main.java
class Main {
    public static void main(String[] args) {
        int r = 2 + 3 * 4;              // 14, not 20
        System.out.println(r);
        System.out.println((2 + 3) * 4);       // 20 with parens

        // Casting changes the interpreted type
        double avg = (double)(10 + 7) / 3;
        System.out.println(avg);           // 5.666...

        // Without the cast both sides are int → avg = 5.0 (after widen)
        System.out.println((10 + 7) / 3);
    }
}
Higher precedence ───────────────────────────▶ Lower precedence () [] . ++ -- ~ ! * / % + - << >> >>> < <= > >= == != & ^ | && || ?: = += … সন্দেহ হলে — parens ব্যবহার করুন; পড়ার সুবিধাই সবার আগে। Figure 7.1 — Java operator precedence (simplified)।

7. Vocabulary

TermMeaningবাংলায়
OperandA value an operator acts on.operator-এর ইনপুট মান।
ExpressionA combination of values + operators producing a value.মান ও operator মিলে তৈরি expression।
Short-circuitSkipping the 2nd operand when result is known.প্রথম operand থেকেই result জানা গেলে দ্বিতীয়টি skip।
Integer division/ on two ints; truncates fractional part.দুটি int-এ ভাগ — ভগ্নাংশ বাদ।
CastExplicit type conversion (T) x.স্পষ্ট type রূপান্তর।
PrecedenceWhich operator binds first.কোন operator আগে চলবে।

8. Practice Problems

  1. Compute the average of 85, 92, and 76 as a floating-point number using a cast.
    তিনটি integer মার্ক-এর দশমিক গড় বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            int a = 85, b = 92, c = 76;
            double avg = (double)(a + b + c) / 3;
            System.out.printf("Average = %.2f%n", avg);
        }
    }
  2. Print whether each of 1..10 is odd or even using the bitwise trick n & 1.
    1 থেকে 10-এর মধ্যে কোনটি odd/even — n & 1 দিয়ে।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            for (int n = 1; n <= 10; n++) {
                System.out.println(n + " : " + ((n & 1) == 0 ? "even" : "odd"));
            }
        }
    }
  3. Rewrite "double the amount and add 100" using compound assignment operators.
    "amount-কে দ্বিগুণ করে ১০০ যোগ" — compound assignment দিয়ে।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            int amount = 250;
            amount *= 2;
            amount += 100;
            System.out.println(amount);
        }
    }
  4. Why does if (user != null && user.isActive()) avoid a NullPointerException, while if (user.isActive() && user != null) does not?
    উপরের দুটি condition-এর পার্থক্য ব্যাখ্যা করুন।
    ✨ Show Answer (উত্তর দেখুন)

    Answer: The first form uses short-circuit AND — && evaluates left to right and stops if the left side is false. So if user is null, user.isActive() is never called. In the second form user.isActive() is called first; if user is null you get an NPE before the null check ever runs. Always put the null guard first.

  5. Use Integer.toBinaryString to print the binary form of 42 and 170 and then their XOR.
    42 ও 170-এর binary এবং তাদের XOR print করুন।
    ✨ Show Answer (উত্তর দেখুন)
    Main.java
    class Main {
        public static void main(String[] args) {
            int a = 42, b = 170;
            System.out.println(Integer.toBinaryString(a));
            System.out.println(Integer.toBinaryString(b));
            System.out.println(Integer.toBinaryString(a ^ b));
            System.out.println("XOR = " + (a ^ b));
        }
    }

Summary — Module 07

Four families — arithmetic, comparison, logical, bitwise. Integer division truncates; cast one operand to double for a fractional result. Use .equals(), not ==, to compare object values. Short-circuit && / || are your friend — put cheap/safe checks first. Bitwise operators power flags, hashing, and low-level tricks; they are not just for systems programmers. When in doubt, parenthesise.

চারটি পরিবার — arithmetic, comparison, logical, bitwise। integer division truncate করে — দশমিকের জন্য cast। object-এ == নয়, .equals()। short-circuit নিরাপদ null check দেয়। সন্দেহ হলে parens।

Next Module → Scanner, printf, and professional I/O in Java.