Java Programming
Lecture 04: Operators & Expressions
Course: 4343203 - Java Programming
GTU Semester 4 | Unit 1
Learning Objectives:
- Master all Java operator categories
- Understand operator precedence and associativity
- Apply operators in complex expressions
- Learn type promotion in expressions
- Handle special operators and their usage
Java Operators Overview
Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
Operator Categories:
- Arithmetic Operators (+, -, *, /, %)
- Relational Operators (==, !=, <, >, <=, >=)
- Logical Operators (&&, ||, !)
- Bitwise Operators (&, |, ^, ~, <<, >>)
- Assignment Operators (=, +=, -=, *=, /=)
- Unary Operators (++, --, +, -, !)
- Ternary Operator (?:)
Key Concepts:
- Precedence: Order of evaluation
- Associativity: Direction of evaluation
- Type Promotion: Automatic type conversion
- Short-circuit: Early evaluation termination
Arithmetic Operators
Basic Arithmetic:
int a = 15, b = 4;
int sum = a + b; // 19
int difference = a - b; // 11
int product = a * b; // 60
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 3 (modulus)
// Floating-point division
double result = (double) a / b; // 3.75Unary Operators:
int x = 10;
int positive = +x; // +10
int negative = -x; // -10
// Pre-increment/decrement
int preInc = ++x; // x=11, preInc=11
int preDec = --x; // x=10, preDec=10
// Post-increment/decrement
int postInc = x++; // postInc=10, x=11
int postDec = x--; // postDec=11, x=10Operator Behavior:
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 15 / 3 | 5 |
| % | Modulus | 15 % 4 | 3 |
| ++ | Increment | ++x | x+1 |
| -- | Decrement | --x | x-1 |
Important Notes:
- Integer division truncates decimal part
- Modulus gives remainder of division
- Pre-increment: increment then use
- Post-increment: use then increment
Relational (Comparison) Operators
Comparison Operations:
int a = 10, b = 20, c = 10;
boolean equal = (a == c); // true
boolean notEqual = (a != b); // true
boolean less = (a < b); // true
boolean greater = (a > b); // false
boolean lessEqual = (a <= c); // true
boolean greaterEqual = (a >= b); // false
// String comparison (special case)
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
boolean strEqual1 = (str1 == str2); // true (string pool)
boolean strEqual2 = (str1 == str3); // false (different objects)
boolean strEqual3 = str1.equals(str3); // true (content comparison)Relational Operators Table:
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal | 5 != 3 | true |
| < | Less than | 3 < 5 | true |
| > | Greater than | 5 > 3 | true |
| <= | Less or equal | 3 <= 5 | true |
| >= | Greater or equal | 5 >= 5 | true |
Key Points:
- All relational operators return boolean
- Use == for primitive comparison
- Use .equals() for object comparison
- Can chain comparisons: 1 < x < 10 ❌
- Correct chaining: (1 < x) && (x < 10) ✅
Logical Operators
Logical AND (&&) - Short-circuit:
boolean result1 = true && true; // true
boolean result2 = true && false; // false
boolean result3 = false && true; // false
boolean result4 = false && false; // false
// Short-circuit behavior
int x = 5;
boolean test = (x > 10) && (++x > 0);
// x is still 5 because ++x is not evaluatedLogical OR (||) - Short-circuit:
boolean result1 = true || true; // true
boolean result2 = true || false; // true
boolean result3 = false || true; // true
boolean result4 = false || false; // false
// Short-circuit behavior
int y = 5;
boolean test2 = (y < 10) || (++y > 0);
// y is still 5 because ++y is not evaluatedLogical NOT (!):
boolean flag = true;
boolean notFlag = !flag; // false
boolean result = !(5 > 3); // false
boolean complex = !(x > 0 && y < 10); // De Morgan's lawTruth Tables:
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
Short-Circuit Evaluation:
- &&: If first is false, second is not evaluated
- ||: If first is true, second is not evaluated
- Improves performance and prevents errors
Assignment Operators
Simple Assignment:
int x = 10; // Basic assignment
int y = x; // Assign value of x to y
boolean flag = true; // Boolean assignment
// Multiple assignments (right to left)
int a, b, c;
a = b = c = 5; // All variables get value 5Compound Assignment:
int num = 10;
num += 5; // num = num + 5; → 15
num -= 3; // num = num - 3; → 12
num *= 2; // num = num * 2; → 24
num /= 4; // num = num / 4; → 6
num %= 5; // num = num % 5; → 1
// String concatenation assignment
String msg = "Hello";
msg += " World"; // msg = msg + " World"; → "Hello World"Assignment Operators Table:
| Operator | Example | Equivalent |
|---|---|---|
| = | x = 5 | x = 5 |
| += | x += 3 | x = x + 3 |
| -= | x -= 3 | x = x - 3 |
| *= | x *= 3 | x = x * 3 |
| /= | x /= 3 | x = x / 3 |
| %= | x %= 3 | x = x % 3 |
| &= | x &= 3 | x = x & 3 |
| |= | x |= 3 | x = x | 3 |
| ^= | x ^= 3 | x = x ^ 3 |
Benefits of Compound Operators:
- More concise code
- Potentially better performance
- Reduces typing errors
- Automatic type casting when needed
Ternary Operator (?:)
Syntax & Basic Usage:
// Syntax: condition ? value1 : value2
int a = 10, b = 20;
// Find maximum
int max = (a > b) ? a : b; // max = 20
// Find minimum
int min = (a < b) ? a : b; // min = 10
// Check even/odd
String result = (a % 2 == 0) ? "Even" : "Odd"; // "Even"
// Absolute value
int num = -15;
int absolute = (num < 0) ? -num : num; // 15Nested Ternary:
int marks = 85;
String grade = (marks >= 90) ? "A" :
(marks >= 80) ? "B" :
(marks >= 70) ? "C" :
(marks >= 60) ? "D" : "F";
// grade = "B"Ternary vs if-else:
// Using ternary operator
int x = 5, y = 10;
int max1 = (x > y) ? x : y;
// Equivalent if-else
int max2;
if (x > y) {
max2 = x;
} else {
max2 = y;
}Complex Expressions:
int age = 20;
boolean hasLicense = true;
String canDrive = (age >= 18) ?
(hasLicense ? "Can drive" : "Need license") :
"Too young";
// Type compatibility
double result = (x > 0) ? x : -1.5; // int promoted to doubleWhen to Use Ternary:
- Simple conditional assignments
- Single-line conditions
- Method return values
- Avoid for complex logic
Operator Precedence & Associativity
Precedence Rules (High to Low):
| Level | Operators | Associativity |
|---|---|---|
| 1 | () [] . | Left to Right |
| 2 | ++ -- ! ~ + - (unary) | Right to Left |
| 3 | * / % | Left to Right |
| 4 | + - (binary) | Left to Right |
| 5 | << >> >>> | Left to Right |
| 6 | < <= > >= instanceof | Left to Right |
| 7 | == != | Left to Right |
| 8 | & | Left to Right |
| 9 | ^ | Left to Right |
| 10 | | | Left to Right |
| 11 | && | Left to Right |
| 12 | || | Left to Right |
| 13 | ?: | Right to Left |
| 14 | = += -= *= /= %= | Right to Left |
Precedence Examples:
// Expression evaluation examples
int result1 = 5 + 3 * 2; // 11 (not 16)
int result2 = (5 + 3) * 2; // 16
boolean test1 = 5 > 3 && 2 < 4; // true
boolean test2 = !false || true && false; // true
// Associativity examples
int a = 10, b = 5, c = 2;
int result3 = a - b - c; // (10-5)-2 = 3
int result4 = a = b = c; // a = (b = c) = 2
// Mixed operators
int x = 5;
int result5 = ++x * 2 + --x; // 6*2 + 5 = 17Best Practices:
- Use parentheses for clarity
- Break complex expressions into steps
- Don't rely on precedence memory
- Consider readability over brevity
Previous Year Exam Questions
Q1. (GTU Summer 2022) Explain operator precedence in Java with examples. What is the difference between ++i and i++?
Solution:
Operator Precedence:
Operator precedence determines the order in which operators are evaluated in an expression.
int result = 5 + 3 * 2; // Result is 11, not 16
// Explanation: * has higher precedence than +
// So: 5 + (3 * 2) = 5 + 6 = 11
int result2 = (5 + 3) * 2; // Result is 16
// Parentheses have highest precedence++i vs i++ (Pre-increment vs Post-increment):
- ++i (Pre-increment): Increment first, then use the value
- i++ (Post-increment): Use the value first, then increment
int i = 5;
int a = ++i; // i becomes 6, then a = 6
int b = i++; // b = 6, then i becomes 7
System.out.println("i = " + i + ", a = " + a + ", b = " + b);
// Output: i = 7, a = 6, b = 6Q2. (GTU Winter 2021) Write a Java program to demonstrate the use of all types of operators.
Solution:
public class OperatorDemo {
public static void main(String[] args) {
// Arithmetic Operators
System.out.println("=== Arithmetic Operators ===");
int a = 15, b = 4;
System.out.println("a + b = " + (a + b)); // 19
System.out.println("a - b = " + (a - b)); // 11
System.out.println("a * b = " + (a * b)); // 60
System.out.println("a / b = " + (a / b)); // 3
System.out.println("a % b = " + (a % b)); // 3
// Unary Operators
System.out.println("\n=== Unary Operators ===");
int x = 10;
System.out.println("x = " + x); // 10
System.out.println("++x = " + (++x)); // 11
System.out.println("x++ = " + (x++)); // 11
System.out.println("x = " + x); // 12
System.out.println("--x = " + (--x)); // 11
System.out.println("x-- = " + (x--)); // 11
System.out.println("x = " + x); // 10
// Relational Operators
System.out.println("\n=== Relational Operators ===");
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
// Logical Operators
System.out.println("\n=== Logical Operators ===");
boolean p = true, q = false;
System.out.println("p && q: " + (p && q)); // false
System.out.println("p || q: " + (p || q)); // true
System.out.println("!p: " + (!p)); // false
// Assignment Operators
System.out.println("\n=== Assignment Operators ===");
int num = 10;
System.out.println("num = " + num); // 10
num += 5; System.out.println("num += 5: " + num); // 15
num -= 3; System.out.println("num -= 3: " + num); // 12
num *= 2; System.out.println("num *= 2: " + num); // 24
num /= 4; System.out.println("num /= 4: " + num); // 6
// Ternary Operator
System.out.println("\n=== Ternary Operator ===");
int max = (a > b) ? a : b;
System.out.println("Maximum of " + a + " and " + b + " is: " + max);
String result = (a % 2 == 0) ? "Even" : "Odd";
System.out.println(a + " is " + result);
}
}Q3. (GTU Summer 2020) What is short-circuit evaluation in logical operators? Explain with examples.
Solution:
Short-Circuit Evaluation: A feature where the second operand of a logical operator is not evaluated if the result can be determined from the first operand alone.
Short-Circuit AND (&&):
int x = 5;
boolean result = (x > 10) && (++x > 0);
System.out.println("x = " + x + ", result = " + result);
// Output: x = 5, result = false
// Explanation: Since (x > 10) is false, ++x is not executed
// The entire expression is false regardless of second conditionShort-Circuit OR (||):
int y = 5;
boolean result2 = (y < 10) || (++y > 0);
System.out.println("y = " + y + ", result2 = " + result2);
// Output: y = 5, result2 = true
// Explanation: Since (y < 10) is true, ++y is not executed
// The entire expression is true regardless of second conditionBenefits of Short-Circuit Evaluation:
- Performance: Avoids unnecessary computations
- Safety: Prevents errors from null pointers
- Efficiency: Reduces execution time
// Practical example - null safety
String str = null;
if (str != null && str.length() > 0) { // Safe - no NullPointerException
System.out.println("String is not empty");
}Lecture Summary
Key Concepts Covered:
- All operator categories and their usage
- Operator precedence and associativity rules
- Type promotion in expressions
- Short-circuit evaluation in logical operators
- Pre vs post increment/decrement
- Ternary operator for conditional expressions
- Compound assignment operators
Learning Outcomes Achieved:
- ✅ Master all Java operator types
- ✅ Apply precedence rules correctly
- ✅ Use operators in complex expressions
- ✅ Understand short-circuit evaluation
- ✅ Handle type promotion effectively
- ✅ Write efficient conditional code
- ✅ Debug expression evaluation issues
Next Lecture: Control Flow - Selection Statements
Topics: if-else statements, nested conditions, switch statements, conditional logic patterns
Thank You!
Questions & Discussion
Next: Lecture 05 - Control Flow (Selection Statements)
Course: 4343203 Java Programming
Unit 1: Introduction to Java
GTU Semester 4

