Ch2: Operators and Statements Flashcards
What is an operator?
A symbol applied to a set of variables that returns a result
What is an operand?
The value(s) that operators operate on
What is the name for the values an operator operates on?
Operands
What are the three types of operators (based on operand count)?
unary, binary, and ternary
What happens if two operators have the same level of precedence?
Java guarantees left-to-right evaluation
What is the order of operator precedence?
- Post-unary de/increment (x++)
- Pre-unary de/increment (++x)
- negation (unary)
- Multiplicative
- Additive
- Shift (bitwise)
- Relational (greater than/less than)
- Equality Operators
- Logical/bitwise operators
- Short-circuit logical
- Ternary
- Assignment
What is the % operator name and function?
Modulus, returns remainder (from devision)
What are the rules of numeric promotion when performing operations on primitive (non-unary) numeric types?
- A smaller type will be promoted to match the larger type
- An integral type will be promoted to match the floating-point type
- For binary arithmetic operators (not unary), byte, short, and char are always promoted to int
- The resulting value of an operator will be the same type as the promoted operands
What are the unary operators?
++ (increment a value by one)
– (decrement a value by one)
+ (makes a literal positive. Opposite of -)
- (makes a literal negative or negates an expression)
! (inverts a boolean, “logical complement operator”)
What does the post-increment operator do?
x++
- Returns original operand value
- Increments operand by one
What does the pre-increment operator do?
++x
- Increments operand by one
- Returns the new value
How do you cast a larger primitive number type to a smaller primitive data type, and what happens?
use (type) (eg, int i = (int) 1.0). Will cause underflow or overflow, which basically wraps around the value
Considering numeric promotion, does this throw an error, and why/not:
long x = 10;
int y = 5;
y *= x;
No; compound assignment operators will automatically re-cast to the target data type.
Considering numeric promotion, does this throw an error, and why/not:
long x = 10;
int y = 5;
y = y * x;
Yes; binary operators return the data type of the larger operand type.
Do assignment operators have a return value
Yes, it returns the value that was assigned to the left-hand operand and therefore can be used like this:
y = (x = 3); // x and y == 3