Chapter 2 Flashcards
Order of operators?
Post unary: x++, x-- Pre unary: ++x, --x Other unary: +,-,! Multiplication etc: *,/,% Addition etc: +,- Shift operators: <>,>>> Relational operators: ,<=,instanceof Equal to etc: ==, != Logical operators: &,^,| Short circuit: &&, || Ternary: boolean?exp1:exp2 Assignment ops: =,+=,*= etc
4 numeric promotion rules:
Java promotes to larger of the data types.
Integral promoted to floating point.
Byte, short and char promoted to Int first, even if none are Int.
The result has same data type as promoted operands.
What is data type of x * y / z?
short x = 14;
Float y = 13;
Double z = 30;
X promoted to Int, then to float. Result of x*y promoted to double. Result is a double.
–x means?
Operator applied first, value return is the new value.
X–
Original value is returned, then the operator is applied.
Int x = 3;
Int y = ++x * 5 / x– + –x;
X?
Y?
X is 2
Y is 7
short z = x * y;
Doesn’t compile, why?
Because short values are automatically promoted to Int when applying arithmetic operator. And short variable cannot be set to Int value.
Which works? long x = 10; int y = 5; A) y *= x; B) y = y * x;
A works. B does not compile.
Is this valid:
long x = (x = 3);
Yes
X ^ Y = ?
1) t t
2) t f
3) f t
4) f f
1) false
2) true
3) true
4) false
Difference between & an &&?
&& short circuits and right hand side of a statement may never be evaluated.
Why does this not through exception:
Integer x;
If(x != null && x.getValue() < 5) {}
Because && short circuit prevents x.getValue() from ever being reached.
File x = new File("s.txt"); File y = new File("s.txt"); File z = x; A) x == y ? B) x == z ?
Checks references point to same object, not for object equivalence. So…
A) false
B) true
Write the following as if else’s:
Int y = 10;
Int x = (y > 5) ? (2 * y) : (3 * y);
Int y = 10; Final Int x; If (y > 5) { X = 2 * y; } else { X = 3 * t; }
What target types can a switch statement have?
Seitch(targetType) {}
int and all primitives that can be promoted to int (byte, short, char). Also enum. Also Byte, Short, Charachter, Integer. Also String.