Skip to content

Information Technology · Ch 2 — Introduction to Programming

Operators and Expressions

3

Operators and Expressions

An operator is a symbol that performs an operation on one or more values (operands); an expression combines operands and operators to produce a result, e.g. total = price * quantity.

Arithmetic operators

+ add, - subtract, * multiply, / divide, % remainder (modulus).

int a = 17, b = 5;
System.out.println(a + b);   // 22
System.out.println(a / b);   // 3   (integer division drops the decimal)
System.out.println(a % b);   // 2   (remainder of 17 / 5)

Note that when both operands are integers, / gives an integer result — 17 / 5 is 3, not 3.4. To get a decimal result, at least one operand must be a decimal type: 17.0 / 5 is 3.4.

Relational (comparison) operators

== equal to, != not equal to, >, <, >=, <=. Each produces a boolean (true/false). Note that == compares while = assigns — mixing them up is a very common mistake.

Logical operators

&& (AND — true only if both sides are true), || (OR — true if either side is true), ! (NOT — reverses a truth value). These combine conditions:

int marks = 72;
boolean firstClass = (marks >= 60) && (marks < 75);   // true

Assignment and shorthand operators

= assigns a value. Shorthand forms combine arithmetic with assignment: x += 5 means x = x + 5; similarly -=, *=, /=, %=. The increment ++ and decrement -- operators add or subtract 1: count++ is count = count + 1.

Operator precedence …

Definition 1Operator

A symbol (such as +, *, ==, &&) that performs an operation on one or …

Definition 2Modulus (%)

The operator that returns the remainder of a division, e.g. `17 …

Definition 3Relational operator

A comparison operator (==, !=, >, <, >=, <=) that yields a bo …

Definition 4Logical operator

&& (AND), || (OR) and ! (NOT), used to combine or negate boolea …

Definition 5Operator precedence

The order in which operators are evaluated in an expression; parentheses override the …