Operators & Statements Flashcards
Is the following assignment valid? short = short + short;
No. short is always promoted to int before being used in an arithmetic binary operation, which cannot be assigned back to short.
Is the following assignment valid? int = byte + short;
Yes. byte and short are automatically promoted to int before added.
Is the following assignment valid? short = short++;
Yes. Unary operators don’t promote shorts.
Is the following assignment valid? float f = 4.3;
No. floating-point literals are assumed to be doubles unless postfixed with ‘f’, which cannot be assigned to float.
Is the following assignment valid? double = short + float;
Yes. short is promoted to int automatically, then to float to be added, then the result is promoted to double to be assigned.
Is the following assignment valid? boolean b = !0;
No. The negation operator is not valid on a numeric value.
Is the following assignment valid? int i = 5.0;
No. 5.0 is treated as a double, which cannot be assigned to an int unless casted.
Is the following assignment valid? short s = 35000;
No. 35000 exceeds the maximum value of short and can’t be assigned unless casted, and then overflowing would apply.
Is the following assignment valid? long l = 35000;
Yes.
Is the following assignment valid? long l = 2500000000;
No. 2500000000 exceeds the maximum value of an int. An ‘L’ must follow the literal value to be treated as a long literal.
Is the following assignment valid? boolean b = int == null;
No. null cannot be compared to primitives
Is the following assignment valid? boolean b = Boolean == null;
Yes.
Given int x = 2;, What is the value of the following expression?
x++ + (2 + –x) * ++x;
- The unary operators are evaluated left to right regardless of parentheses, which simplifies to:
2 + (2 + 2) * 3;
Which of the following types is not supported by switch statements? byte/Byte, short/Short, char/Character, int/Integer, long/Long, enum, String.
long/Long (enum support added in Java 5, String in Java 7)
What is a Java operator?
It is a special symbol that can be applied to a set of variables, values, or literals that returns a result.
What is an operand in the context of an operator in Java?
An operand is one of set of variables, values, or literals, which can be used to return a result from an operator.