Topic 4: Operators in Java
📖 6 min read · 🎯 beginner · 🧭 Prerequisites: java-day-i-introduction-to-oops, android-application-structure-folder-structure
Why this matters
Here's the thing — data on its own does nothing. Your app stores a user's age, a product's price, a login attempt count. But the moment you need to do something with that data — add a discount, check if a password matches, decide which screen to show next — you reach for operators. They're the symbols that make your code actually think. Java has seven families of them, and once you know which family does what, you'll start reading and writing logic naturally. Let's walk through all of them.
What You'll Learn
- Perform calculations with all five arithmetic operators
- Compare values using the six relational operators and combine conditions with logical operators
- Manipulate individual bits using Java's seven bitwise operators
- Assign and update variable values with compound assignment operators
- Apply unary operators and the ternary operator for concise, expressive code
The Analogy
Think of Java operators as the tools hanging on a master craftsperson's pegboard. The hammer (arithmetic) shapes raw material; the caliper (relational) measures and compares; the level (logical) checks whether two conditions align; the jeweler's loupe (bitwise) inspects individual bits like facets on a gem; the clamp (assignment) locks a value in place; the chisel (unary) makes a single precise adjustment; and the template (ternary) stamps out an if-else decision in one swift motion. Knowing which tool to reach for — and when — is what separates a journeyman from a master builder.
Chapter 1: Arithmetic Operators
Arithmetic operators perform the basic mathematical operations you learned in school: addition, subtraction, multiplication, division, and modulus (remainder after division).
| Operator | Meaning |
|---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus (remainder) |
public class ArithmeticOperators {
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
System.out.println("a / b = " + (a / b)); // 3 (integer division — decimal truncated)
System.out.println("a % b = " + (a % b)); // 1
}
}
Note that / on two int operands performs integer division — the fractional part is discarded. 10 / 3 yields 3, not 3.333…. Use double operands when you need the decimal.
Chapter 2: Relational Operators
Relational operators compare two values and always return a boolean — either true or false. They are the backbone of every if, while, and for condition in your Android code.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("a == b: " + (a == b)); // false
System.out.println("a != b: " + (a != b)); // true
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("a <= b: " + (a <= b)); // false
}
}
Watch out: Use
==to compare primitives (int,boolean, etc.). ForStringand other objects, use.equals()—==checks reference identity, not content equality.
Chapter 3: Logical Operators
Logical operators combine or invert boolean expressions, letting you express multi-condition rules like "the user is logged in AND has an active subscription."
| Operator | Meaning |
|---|---|
&& | Logical AND — true only when both operands are true |
|| | Logical OR — true when at least one operand is true |
! | Logical NOT — inverts the boolean value |
public class LogicalOperators {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y)); // false
System.out.println("x || y: " + (x || y)); // true
System.out.println("!x: " + (!x)); // false
}
}
&& and || are short-circuit operators: Java stops evaluating as soon as the result is determined. If the left side of && is false, the right side is never evaluated — useful when the right side has side effects or could throw a NullPointerException.
Chapter 4: Bitwise Operators
Bitwise operators work directly on the binary representation of integer values — each bit is processed individually. They appear frequently in Android permissions flags, drawing operations, and low-level data parsing.
| Operator | Meaning |
|---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise NOT (one's complement) |
<< | Left shift |
>> | Right shift (sign-extended) |
>>> | Unsigned right shift (zero-filled) |
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
System.out.println("a & b: " + (a & b)); // 0001 => 1
System.out.println("a | b: " + (a | b)); // 0111 => 7
System.out.println("a ^ b: " + (a ^ b)); // 0110 => 6
System.out.println("~a: " + (~a)); // 1010 => -6
System.out.println("a << 1: " + (a << 1)); // 1010 => 10
System.out.println("a >> 1: " + (a >> 1)); // 0010 => 2
System.out.println("a >>> 1: " + (a >>> 1)); // 0010 => 2
}
}
~a flips every bit. For a 32-bit int holding 5 (…0101), the result is …1010, which in two's complement is -6. << by 1 is equivalent to multiplying by 2; >> by 1 is equivalent to dividing by 2 (preserving sign).
flowchart LR
A["a = 5 (0101)"] --> AND["& 3 (0011) → 0001 = 1"]
A --> OR["| 3 (0011) → 0111 = 7"]
A --> XOR["^ 3 (0011) → 0110 = 6"]
A --> NOT["~a → ...11111010 = -6"]
A --> SHL["<< 1 → 1010 = 10"]
A --> SHR[">> 1 → 0010 = 2"]
Chapter 5: Assignment Operators
Assignment operators store a value into a variable. The compound forms (+=, -=, etc.) combine an arithmetic operation with the assignment, keeping code concise and reducing repetition.
| Operator | Equivalent to |
|---|---|
= | Simple assignment |
+= | a = a + b |
-= | a = a - b |
*= | a = a * b |
/= | a = a / b |
%= | a = a % b |
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;
a += b;
System.out.println("a += b: " + a); // 15
a -= b;
System.out.println("a -= b: " + a); // 10
a *= b;
System.out.println("a *= b: " + a); // 50
a /= b;
System.out.println("a /= b: " + a); // 10
a %= b;
System.out.println("a %= b: " + a); // 0
}
}
Chapter 6: Unary Operators
Unary operators act on a single operand. The pre/post distinction of ++ and -- is one of Java's most common gotcha zones for beginners.
| Operator | Meaning |
|---|---|
+ | Unary plus (promotes the operand to int if smaller) |
- | Unary minus (negates the value) |
++ | Increment by 1 |
-- | Decrement by 1 |
! | Logical NOT (boolean operand) |
public class UnaryOperators {
public static void main(String[] args) {
int a = 10;
System.out.println("+a: " + (+a)); // 10
System.out.println("-a: " + (-a)); // -10
System.out.println("++a: " + (++a)); // 11 — increments FIRST, then uses value
System.out.println("--a: " + (--a)); // 10 — decrements FIRST, then uses value
System.out.println("a++: " + (a++)); // 10 — uses value FIRST, then a becomes 11
System.out.println("a--: " + (a--)); // 11 — uses value FIRST, then a becomes 10
}
}
Pre-increment (++a) modifies a before the expression is evaluated. Post-increment (a++) returns the current value first, then increments. This distinction matters inside loops and method arguments.
Chapter 7: The Ternary Operator
The ternary (conditional) operator ?: is a one-line if-else. It takes three operands — a condition, a value if true, and a value if false — and evaluates to whichever value matches the condition.
condition ? valueIfTrue : valueIfFalse
public class TernaryOperator {
public static void main(String[] args) {
int a = 10;
int b = 5;
String result = (a > b) ? "a is greater" : "b is greater";
System.out.println(result); // "a is greater"
}
}
Use the ternary when you need a value from a simple two-branch decision. For complex multi-branch logic, prefer a full if-else block for readability.
🧪 Try It Yourself
Task: Write a Java program that:
- Declares two integers,
x = 17andy = 5. - Prints the result of every arithmetic operator applied to them.
- Uses the ternary operator to print whether
x % yis even or odd.
Success criterion: Your console output should end with either "Remainder is even" or "Remainder is odd" — and for 17 % 5 = 2, the answer is "Remainder is even".
Starter snippet:
public class OperatorPractice {
public static void main(String[] args) {
int x = 17;
int y = 5;
// 1. Arithmetic
System.out.println("x + y = " + (x + y));
System.out.println("x - y = " + (x - y));
System.out.println("x * y = " + (x * y));
System.out.println("x / y = " + (x / y));
System.out.println("x % y = " + (x % y));
// 2. Ternary — fill this in
String parity = /* your ternary here */ "";
System.out.println("Remainder is " + parity);
}
}
🔍 Checkpoint Quiz
Q1. What is the difference between >> and >>> in Java?
A) >> shifts left; >>> shifts right
B) >> preserves the sign bit; >>> always fills vacated bits with 0
C) >> works on floats; >>> works only on ints
D) They are identical; >>> is just an alias
Q2. Given the following snippet, what does the output of the last two lines show?
int a = 10;
System.out.println("a++: " + (a++));
System.out.println("a: " + a);
A) a++: 11 then a: 11
B) a++: 10 then a: 10
C) a++: 10 then a: 11
D) a++: 11 then a: 10
Q3. Which of the following compound assignment expressions correctly reduces score by 10 percent?
A) score -= 10;
B) score *= 0.9;
C) score /= 10;
D) score %= 0.9;
Q4. You want to check whether a user is an admin AND their session is active. Rewrite the following using Java logical operators and a ternary to produce the string "Access granted" or "Access denied":
boolean isAdmin = true;
boolean isSessionActive = false;
// Your one-liner here
A1. B — >> is a signed right shift that replicates the sign bit (so negative numbers stay negative); >>> is an unsigned right shift that always fills vacated high-order bits with 0, treating the value as unsigned.
A2. C — Post-increment returns the current value (10) to println first, then increments a to 11. The next line reads the already-incremented a.
A3. B — score *= 0.9 multiplies the current score by 0.9, which is the same as subtracting 10%. Option A subtracts a flat 10 points; option C divides by 10; option D uses modulus, which is wrong here.
A4. String access = (isAdmin && isSessionActive) ? "Access granted" : "Access denied"; — && requires both conditions to be true; since isSessionActive is false, the result is "Access denied".
🪞 Recap
- Java provides seven operator categories: arithmetic, relational, logical, bitwise, assignment, unary, and ternary.
- Relational operators always return
boolean; use.equals()for object comparison, not==. &&and||short-circuit — the right operand is skipped when the result is already determined.- Pre-increment (
++a) modifies before use; post-increment (a++) uses then modifies — a common source of bugs. - The ternary operator
condition ? a : bis a concise one-line if-else for simple two-branch decisions.
📚 Further Reading
- Java Language Specification — Operators — the authoritative reference for operator precedence and evaluation rules
- Oracle Java Tutorials — Operators — beginner-friendly walkthrough with runnable examples
- Bitwise and Bit Shift Operators (Baeldung) — deeper dive into bitwise use cases including Android permission flags
- ⬅️ Previous: Android Application Structure & Folder Structure
- ➡️ Next: Abstraction in Java