The mod operator % returns the remainder of a division (e.g., 4 % 3 equals 1).
Unary operators are shortcuts:
x++ is equivalent to x = x + 1.
x-- is equivalent to x = x - 1.
x *= 3 is equivalent to x = x * 3.
The not operator ! with a boolean negates the value (e.g., if z is true, !z is false).
Division with int and double
int division truncates the decimal portion (e.g., 5 / 3 equals 1).
double division results in a decimal value if one or both operands are doubles (e.g., 5.0 / 3 is a double division, resulting in 1.666...).
Dividing an int by zero results in an ArithmeticException.
Dividing a double by zero results in:
Positive infinity if the numerator is positive.
Negative infinity if the numerator is negative.
NaN (Not a Number) if both the numerator and denominator are zero.
Operator Precedence
Operator precedence determines the order of execution.
Use parentheses to clarify the order of execution.
Simplified precedence table (highest to lowest):
Parentheses ()
Increment/Decrement ++, --, and Not !
Casting (int), (double)
Multiplication *, Division /, Mod %
Addition +, Subtraction -
Comparative Operators (e.g., >, <)
Operators with the same precedence are generally processed from left to right.
Casting and Overflow
Casting converts a piece of data from one primitive type to another.
Widening: Converting to a data type with more precision or space (e.g., int to double). This can happen automatically.
Narrowing: Converting to a data type with less precision or space (e.g., double to int). This must be done manually.
When casting a double to an int, the decimal portion is truncated (not rounded).
int values range from approximately -2,000,000,000 to 2,000,000,000.
byte values range from -128 to 127.
Overflow: Occurs when a number is larger than the data type can hold.
byte, short, int, and long will wrap around to the other side (e.g., adding 1 to a byte with a value of 127 results in -128).
double and float will go to positive or negative infinity.
Swapping Variable Values
The most universal way to swap the values of two variables is with a temporary (temp) variable.
Example: java
int x = 3;
int y = 9;
int temp = x; // Store the value of x in temp
x = y; // Assign the value of y to x
y = temp; // Assign the value of temp (original x) to y