🧮

Java Expressions Overview

Sep 11, 2025

Overview

This lecture explores Java expressions in detail, including their components, types of operators, precedence rules, type conversion, and assignment variations. It also provides practical code examples to illustrate key concepts.

Basics of Expressions

  • An expression in Java is any code that computes or represents a value. It can be:
    • A literal (e.g., 42, 3.14, 'A', "Hello")
    • A variable (e.g., x, total)
    • A function call (e.g., Math.sqrt(9))
    • A combination using operators (e.g., a + b * c)
  • Expressions can be assigned to variables, used as parameters, or combined into more complex expressions.
  • Java provides useful constants:
    • Math.PI (Ï€), Math.E (e)
    • Integer.MAX_VALUE, Integer.MIN_VALUE
    • Double.MAX_VALUE, Double.MIN_VALUE, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN

Arithmetic Operators

  • Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), % (remainder).
  • Work with numeric types (byte, short, int, long, float, double) and char (treated as an integer).
  • Type conversion happens automatically when combining different numeric types:
    • Example: double result = 37.4 + 10; // 10 is converted to 10.0
  • Integer division discards the fractional part:
    • int x = 7 / 2; // x is 3
    • double y = 7.0 / 2; // y is 3.5
  • The % operator computes the remainder:
    • int r = 34577 % 100; // r is 77
    • int even = (N % 2 == 0) ? 1 : 0; // checks if N is even
    • % also works with real numbers: double d = 7.52 % 0.5; // d is 0.02
  • Unary minus (-x) negates a value; unary plus (+x) exists but has no effect.
  • The + operator concatenates strings with other values:
    • String s = "Score: " + 42; // s is "Score: 42"

Increment and Decrement

  • ++ increments and -- decrements a variable by 1. Can be used as prefix or postfix:
    • x++; // same as x = x + 1;
    • --y; // same as y = y - 1;
  • As expressions:
    • int y = x++; // y gets old value of x, x is incremented
    • int z = ++x; // x is incremented, z gets new value
  • Avoid using ++ or -- inside larger expressions to prevent confusion:
    • x = x++; // x remains unchanged
  • Works with char as well:
    • char ch = 'A'; ch++; // ch is now 'B'

Relational Operators

  • Used to compare values, returning a boolean result:
    • == (equal), != (not equal), <, >, <=, >=
    • Example: if (score >= 60) { ... }
  • Work with numeric and char types (comparison based on Unicode value):
    • 'A' < 'a' // true
  • For strings, use equals() or compareTo():
    • if (str1.equals(str2)) { ... }
  • Special case: Double.NaN is not equal to anything, even itself:
    • if (x == Double.NaN) // always false
    • Use Double.isNaN(x) to check for NaN.

Boolean Operators

  • Combine or negate boolean values:
    • && (logical "and"): if (x > 0 && y > 0) { ... }
    • || (logical "or"): if (x == 0 || y == 0) { ... }
    • ! (logical "not"): if (!done) { ... }
  • && and || are short-circuited:
    • In if (x != 0 && y / x > 1), if x is 0, y / x is never evaluated.

Conditional Operator

  • The conditional (ternary) operator selects between two expressions based on a boolean condition:
    • Syntax: booleanExpr ? expr1 : expr2
    • Example:
      int next = (N % 2 == 0) ? (N / 2) : (3 * N + 1);
      // If N is even, next = N/2; else, next = 3*N+1
      

Assignment Operators and Type Conversion

  • = assigns a value; assignment can be used as an expression:
    • if ((A = B) == 0) { ... } // assigns B to A, then checks if A is 0
  • Automatic type conversion occurs from "smaller" to "larger" numeric types:
    • int a = 17; double x = a; // OK
    • short b = a; // Error: no automatic conversion from int to short
  • Type casts force conversion:
    • short b = (short)a; // Explicit cast
    • (int)7.9453 // 7
  • Example: Generating a random integer between 1 and 6:
    int roll = (int)(6 * Math.random()) + 1;
    
  • char and numeric types can be converted:
    • (char)97 // 'a'
    • (int)'+' // 43
    • (char)('A' + 2) // 'C'
  • String conversion:
    • To string: String.valueOf(42) // "42"
    • To int: Integer.parseInt("10") // 10
    • To double: Double.parseDouble("17.42e-2") // 0.1742
  • Combined assignment operators:
    • x += y; // x = x + y;
    • x -= y; // x = x - y;
    • x *= y; // x = x * y;
    • x /= y; // x = x / y;
    • x %= y; // x = x % y;
    • For strings:
      String str = "tire";
      str += 'd'; // str is now "tired"
      

Operator Precedence

  • Operators are evaluated in this order (highest to lowest):
    1. Unary: ++, --, !, unary -, unary +, type-cast
    2. Multiplication/division/remainder: *, /, %
    3. Addition/subtraction: +, -
    4. Relational: <, >, <=, >=
    5. Equality: ==, !=
    6. Boolean and: &&
    7. Boolean or: ||
    8. Conditional: ?:
    9. Assignment: =, +=, -=, *=, /=, %=
  • Operators on the same line have the same precedence.
  • Most operators (except assignment and unary) are evaluated left-to-right.
  • Example:
    • A * B / C is evaluated as (A * B) / C
    • A = B = C is evaluated as A = (B = C)
  • Use parentheses to clarify grouping and avoid mistakes:
    • (A + B) * C vs. A + (B * C)

Key Terms & Definitions

  • Expression: Code that computes a value.
  • Literal: A fixed value written directly in code (e.g., 3.14, "Hello").
  • Type Conversion: Automatic or explicit change of a value from one type to another.
  • Increment/Decrement: Operations (++/--) that add or subtract 1 from a variable.
  • Relational Operator: Compares values, returning a boolean result.
  • Boolean Operator: Combines or negates boolean values (&&, ||, !).
  • Conditional Operator: Ternary operator (?:) that selects between two expressions based on a condition.
  • Type Cast: Explicitly converts a value to another type using (Type).
  • Short-circuit Evaluation: Logical operators that skip evaluating the second operand if not needed.

Action Items / Next Steps

  • Practice using different operators and expressions in Java code.
  • Review operator precedence and use parentheses to clarify expressions.
  • Experiment with type casting and string conversion functions.
  • Try out code examples for increment/decrement, conditional, and assignment operators.
  • Read the related section on string comparison (Subsection 2.3.3) for more detail.