Skip to main content

Java Basics

Operators

Complete lesson for Operators using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Operators

Section: Java Basics. Arithmetic, relational, logical, bitwise, assignment, ternary, instanceof, escapes, and precedence.

What are operators?

  • Operators compute a value from one or more operands. Java has no pointer-dereference, address-of, or scope-resolution operator (* / & / :: as in C++).
  • Integer / and % truncate toward zero. % works for integers; floating % is legal but rarely used in interviews.
  • String + concatenates. If either operand is a String, the other is converted with String.valueOf.
  • Escape sequences inside string and char literals format output: \n newline, \t tab, \\ backslash, \" quote.

Java operators & escape sequences

Operators compute values from operands. The chart groups arithmetic, relational, logical, bitwise (including Java’s >>>), assignment, and other operators (?:, instanceof, new). The right side lists String escapes such as \n and \t. Java has no pointer or sizeof operators.

Java operators and escape sequences chart covering arithmetic, relational, logical, bitwise including unsigned right shift, assignment, ternary instanceof and new, plus string escapes such as newline, tab, backslash, and quotes, with a precedence strip.
Java operators and escapes — from arithmetic and bits to formatted String output
  • Arithmetic / relational / logical: everyday math and decisions; && short-circuits.
  • Bitwise: & | ^ ~ << >> >>> — >>> zero-fills.
  • Other: ?:, instanceof, new, cast, ., [].
  • Escapes: \n, \t, \\, \" inside strings.

Classification (overview)

CategoryOperatorsPurpose
Arithmetic+ - * / % ++ --Math and increment
Relational== != > < >= <=Compare values
Logical&& || !Boolean combine (short-circuit)
Bitwise / shift& | ^ ~ << >> >>>Bit operations on integers
Assignment= += -= *= /= %= &= |= ^= <<= >>= >>>=Store or update
Other?:, instanceof, (), new, ., []Ternary, type test, cast, allocate, member, index

Arithmetic, relational, logical

  • + - * / % follow usual math; unary - negates. ++ / -- as prefix return the updated value; as postfix they return the old value.
  • Relational operators produce boolean. You cannot write if (x) for an int like C — the condition must be boolean.
  • && and || short-circuit: the right operand is skipped if the result is already known. & and | on booleans always evaluate both sides.
  • ! inverts a boolean. == on primitives compares values; on references it compares identity (use .equals for String content).
public class OperatorBasics {
    public static void main(String[] args) {
        int a = 10, b = 3;
        System.out.println(a / b);          // 3
        System.out.println(a % b);          // 1
        System.out.println(a > b && b != 0);
        int max = (a > b) ? a : b;
        System.out.println(max);
        System.out.println("Line1\nLine2");
    }
}

Bitwise operators

  • Work on two’s-complement integers. >>> is unsigned right shift (fills with zeros) — a Java-only spelling compared with C++.
  • n & 1 tests odd; n << 1 multiplies by 2 for non-overflowing values; n ^ n is 0.
  • ~ flips every bit. Combined with masks, & clears, | sets, ^ toggles.
OpNameExample idea
&ANDClear / test bits
|ORSet bits
^XORToggle bits; find unique number
~NOTFlip all bits
<<Left shiftShift toward high bits
>>Signed right shiftKeeps sign bit
>>>Unsigned right shiftFills with 0

Assignment, ternary, and instanceof

  • = is assignment, not equality. Compound forms +=, -=, *=, /=, %= (and the bitwise ones) update in place.
  • condition ? a : b chooses a if the condition is true. Both branches must be assignment-compatible.
  • obj instanceof Type is false for null and does not throw. Pattern matching (if (obj instanceof String s)) is standard from Java 16.
L2

Advanced — Operators

Precedence, associativity, and String +

  • Unary > arithmetic > shift > relational > equality > bitwise AND/XOR/OR > logical &&/|| > ternary > assignment.
  • When unsure, use parentheses. Interviewers love i = i++ style traps — the value of i++ is the old i, then assignment overwrites.
  • String + concatenates and is left-associative: "a" + 1 + 2 is "a12"; 1 + 2 + "a" is "3a".
  • Do not use + to build strings in a tight loop — use StringBuilder.

Short-circuit, side effects, and escapes

  • x != null && x.isEmpty() is safe because isEmpty is skipped when x is null. x != null & x.isEmpty() can NPE.
  • ++ / -- on the same variable twice in one expression is a readability trap; Java defines left-to-right evaluation, but interviews still ask you to avoid it.
  • Common escapes: newline \n, tab \t, backslash \\, double quote, single quote, and Unicode \u plus four hex digits. printf("%n") is a portable newline.
L3

Tricky Interview Points

Q1) What is the difference between && and & for booleans?

Answer && short-circuits; & always evaluates both operands. Use && in conditions to avoid NPEs and extra work.

Q2) What does >>> do?

Answer Unsigned right shift: bits move right and vacated high bits become 0, even for negative ints. >> keeps the sign bit.

Q3) What is 7 / 2 and 7 % 2 in Java?

Answer 3 and 1. Integer division truncates toward zero.

Q4) Does instanceof work on null?

Answer null instanceof AnyType is false and does not throw.

Q5) Why is i = i++ a trap?

Answer The postfix expression yields the old value, then i is incremented, then the assignment writes the old value back. i stays the same.

Q6) Can you overload operators in Java?

Answer No, except that + is overloaded by the language for String concatenation. You cannot define your own operator overloads.

Q7) What is the difference between == and equals for String?

Answer == compares references (identity). equals compares character content. Always use equals for text unless you truly mean the same object.

Q8) What does "a" + 1 + 2 print?

Answer a12. Left-to-right concatenation: ("a" + 1) is "a1", then + 2 is "a12". Contrast 1 + 2 + "a" which is "3a".

Q9) Name four Java escape sequences.

Answer \n newline, \t tab, \\ backslash, \" quote. \uXXXX is a Unicode escape.

Q10) Does Java have a pointer or sizeof operator?

Answer No. There is no * dereference, no & address-of, no ->, and no sizeof. Use . and [] on objects and arrays.

Q11) Which operator tests odd vs even with bits?

Answer n & 1. If the result is 1, n is odd. n << 1 doubles (until overflow); n >> 1 halves toward negative infinity for negatives — be careful.

L4

Simple Programs

Bitwise demo

public class BitwiseDemo {
    public static void main(String[] args) {
        int a = 12; // 1100
        int b = 10; // 1010
        System.out.println(a & b);  // 8
        System.out.println(a | b);  // 14
        System.out.println(a ^ b);  // 6
        System.out.println(a << 1); // 24
        int n = 7;
        System.out.println((n & 1) == 1 ? "odd" : "even");
    }
}

Short-circuit vs both sides

public class ShortCircuit {
    static boolean ping(String label, boolean value) {
        System.out.println(label);
        return value;
    }

    public static void main(String[] args) {
        System.out.println("&& :");
        boolean a = ping("L", false) && ping("R", true);
        System.out.println("|| :");
        boolean b = ping("L", true) || ping("R", false);
        System.out.println(a + " " + b);
    }
}

Ternary max and escape output

public class TernaryEscapes {
    public static void main(String[] args) {
        int x = 9, y = 4, z = 11;
        int max = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
        System.out.println("max = " + max);
        System.out.println("Name:\tAda\nLang:\tJava");
    }
}

instanceof and String + order

public class InstanceConcat {
    public static void main(String[] args) {
        Object o = "hello";
        System.out.println(o instanceof String);
        System.out.println(null instanceof String);
        System.out.println("a" + 1 + 2);
        System.out.println(1 + 2 + "a");
    }
}
L5

Problem Solving Tricks

  • Use && / || in if conditions; reserve & / | for bit masks (or rare non-short-circuit needs).
  • Parenthesize mixed shift and arithmetic expressions.
  • n & (n - 1) clears the lowest set bit — a common interview trick.
  • Do not use + for heavy string building in a loop; use StringBuilder.
  • Memorise >>> as “zero-fill right shift” — that one word separates Java from C++ interviews.
  • == on Integer can lie because of the -128..127 cache; prefer equals or intValue.
  • Write "\n" in source when you want a real newline in the string; "%n" in printf is OS-correct.
  • Put the boolean test first in x != null && x.method() so the method never runs on null.
L6

Practice Programs List

  1. Print AND, OR, XOR, left shift, and both right shifts of two integers.
  2. Write a program that finds the maximum of three ints using only the ternary operator.
  3. Demonstrate short-circuit: skip a method call on the right of && when the left is false.
  4. Check whether an int is a power of two using n > 0 && (n & (n - 1)) == 0.
  5. Predict int i = 5; i = i++; then run it.
  6. Print "a" + 1 + 2 and 1 + 2 + "a" and explain the difference.
  7. Print a two-line label using \n and a column using \t.
  8. Test null instanceof String and a real String with instanceof.
  9. Rewrite nested if-else that picks a grade as a chain of ternary operators (then prefer if-else in real code).
  10. Use >>> on -1 and compare the result with >>.