Variables
3. Examples
3.1. Operators
Definition
An operator is a symbol or keyword that specifies an operation on one or more operands (variables, literals, or expressions) to produce a result. Operators are used within expressions and assignment statements to perform computations or comparisons.
Types of Operators
Arithmetic Operators:
Perform mathematical operations.
Examples: + (addition), - (subtraction), * (multiplication), / (division), % (modulus).
Java Example: int result = 10 + 5; // 15
Note: Division (/) with integers in Java yields an integer (e.g., 5 / 2 = 2). Use floating-point operands for decimal results (e.g., 5.0 / 2 = 2.5).
Assignment Operators:
Assign values to variables or update them.
Examples: = (simple assignment), +=, -=, *=, /=, %= (compound assignment).
Java Example: x += 5; // Equivalent to x = x + 5;
Relational Operators:
Compare values, returning a boolean (true or false).
Examples: == (equal to), != (not equal to), > (greater than), < (less than), >=, <=.
Java Example: boolean isAdult = age >= 18; // true if age is 18 or more
Logical Operators:
Combine boolean expressions.
Examples: && (AND), || (OR), ! (NOT).
Java Example: boolean canVote = isCitizen && age >= 18;
Increment/Decrement Operators:
Increase or decrease a variable’s value by 1.
Examples: ++ (increment), -- (decrement).
Java Example: x++; // Equivalent to x = x + 1;
Note: x++ (post-increment) vs. ++x (pre-increment) affects when the increment occurs in expressions.
Bitwise Operators (less common for beginners):
Operate on binary representations of numbers.
Examples: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), << (left shift), >> (right shift).
Java Example: int result = 5 & 3; // Binary: 101 & 011 = 001 (1)
Ternary Operator:
A concise conditional expression.
Syntax: condition ? valueIfTrue : valueIfFalse
Java Example: String status = age >= 18 ? "Adult" : "Minor";