Programmer I Chapter 3: Operators Flashcards
name 4 Numeric promotion rules
- If two values have different datatypes, Java will automatically promote one of the values to the larger of the two data types.
- If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.
- Smaller data types, namely, byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.
- After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands.
What is the data type of x * y? int x = 1; long y = 33; var z = x * y;
If we follow the first rule, since one of the values is long and the other is int and since long is larger than int, then the int value is promoted to a long, and the resulting value is long.
What is the data type of x + y? double x = 39.21; float y = 2.1; var z = x + y;
This is actually a trick question, as this code will not compile! As you may remember from Chapter 2, floating-point literals are assumed to be double, unless postfixed with an f, as in 2.1f. If the value of y was set properly to 2.1f, then the promotion would be similar to the previous example, with both operands being promoted to a double, and the result would be a double value.
What is the data type of x * y? short x = 10; short y = 3; var z = x * y;
On the last line, we must apply the third rule, namely, that x and y will both be promoted to int before the binary multiplication operation, resulting in an output of type int. If you were to try to assign the value to a short variable without casting, the code would not compile. Pay close attention to the fact that the resulting output is not a short, as we’ll come back to this example in the upcoming “Assigning Values” section.
What is the data type of w * x / y? short w = 14; float x = 13; double y = 30; var z = w * x / y;
In this case, we must apply all of the rules. First, w will automatically be promoted to int solely because it is a short and it’s being used in an arithmetic binary operation. The promoted w value will then be automatically promoted to a float so that it can be multiplied with x. The result of w * x will then be automatically promoted to a double so that it can be divided by y, resulting in a double value.
what lines compile?
float egg = 2.0 / 9;
int tadpole = (int)5 * 2L;
short frog = 3 - 2.0;
none of them
what line causes a compile error?
short mouse = 10;
short hamster = 3;
short capybara = mouse * hamster;
3rd one.
1 and 2 are fine despite the fact that literals are of int type - Java allows for implicit compile-time narrowing of constants.
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
does this compile?
long goat = 10;
int sheep = 5;
sheep *= goat;
Yes.
The compound operator will first cast sheep to a long, apply the multiplication of two long values, and then cast the result to an int.
what will this print?
long wolf = 5;
long coyote = (wolf=3);
System.out.println(wolf);
System.out.println(coyote);
3
3
Assignment expressions are legal
what will this print?
System.out.print(null instanceof Object);
Object noObjectHere = null;
System.out.print(noObjectHere instanceof String);
System.out.print(null instanceof null);
does not compile.
calling instanceof on the null literal or a null reference always returns false. The last line does not compile, since null is used on the right side of the instanceof operator
what is the output?
int rabbit = 6;
boolean bunny = (rabbit >= 6) || (++rabbit <= 7);
System.out.println(rabbit);
Because rabbit >= 6 is true, the increment operator on the right side of the expression is never evaluated, so the output is 6.
what is the output?
int sheep = 1;int zzz = 1;
int sleep = zzz<10 ? sheep++ : zzz++;
System.out.print(sheep+”,”+zzz);
2,1
since the left-hand boolean expression was true, onlysheep was incremented
Which of the following Java operators can be used with booleanvariables? (Choose all that apply.)
A. == B. + C. -- D. ! E. % F. <= G. Cast with (boolean)
A, D, G. Option A is the equality operator and can be used onprimitives and object references. Options B and C are botharithmetic operators and cannot be applied to a boolean value.Option D is the logical complement operator and is usedexclusively with boolean values. Option E is the modulus operator,which can be used only with numeric primitives. Option F is arelational operator that compares the values of two numbers.Finally, option G is correct, as you can cast a boolean variablesince boolean is a type.
What data type (or types) will allow the following code snippet tocompile? (Choose all that apply.)
byte apples = 5;
short oranges = 10;
_______ bananas = apples + oranges;
A. int B. long C. boolean D. double E. short F. byte
A, B, D. The expression apples + oranges is automaticallypromoted to int, so int and data types that can be promotedautomatically from int will work. Options A, B, and D are suchdata types. Option C will not work because boolean is not anumeric data type. Options E and F will not work without anexplicit cast to a smaller data type.
What change, when applied independently, would allow the following code snippet to compile? (Choose all that apply.)
3: long ear = 10;
4: int hearing = 2 * ear;
A. No change; it compiles as is.
B. Cast ear on line 4 to int.
C. Change the data type of ear on line 3 to short.
D. Cast 2 * ear on line 4 to int.
E. Change the data type of hearing on line 4 to short.
F. Change the data type of hearing on line 4 to long.
B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * ear is automatically promoted to long and cannot be automatically stored in hearing, which is in an int value. Options B, C, and D solve this problem by reducing the long value to int. Option E does not solve the problem and actually makes it worse by attempting to place the value in a smaller datatype. Option F solves the problem by increasing the data type of the assignment so that long is allowed.
What is the output of the following code snippet?
3: boolean canine = true, wolf = true;
4: int teeth = 20;
5: canine = (teeth != 10) ^ (wolf=false);
6: System.out.println(canine+”, “+teeth+”, “+wolf);
A. true, 20, true B. true, 20, false C. false, 10, true D. false, 20, false E. The code will not compile because of line 5. F. None of the above
B. The code compiles and runs without issue, so option E is notcorrect. This example is tricky because of the second assignmentoperator embedded in line 5. The expression (wolf=false) assignsthe value false to wolf and returns false for the entireexpression. Since teeth does not equal 10, the left side returnstrue; therefore, the exclusive or (^) of the entire expressionassigned to canine is true. The output reflects these assignments,with no change to teeth, so option B is the only correct answer.
Which of the following operators are ranked in increasing or thesame order of precedence? Assume the + operator is binaryaddition, not the unary form. (Choose all that apply.)
A. +, *, %, -- B. ++, (int), * C. =, ==, ! D. (short), =, !, * E. *, /, %, +, == F. !, ||, & G. ^, +, =, +=
A, C. Options A and C show operators in increasing or the same order of precedence. Options B and E are in decreasing or thesame order of precedence. Options D, F, and G are in neitherincreasing or decreasing order of precedence. In option D, theassignment operator (=) is between two unary operators, with themultiplication operator (*) incorrectly having the highest order orprecedence. In option F, the logical complement operator (!) hasthe highest order of precedence, so it should be last. In option G,the assignment operators have the lowest order of precedence, notthe highest, so the last two operators should be first
What is the output of the following program?
1: public class CandyCounter {
2: static long addCandy(double fruit, float vegetables){
3: return (int)fruit+vegetables;
4: }
5:
6: public static void main(String[] args) {
7: System.out.print(addCandy(1.4, 2.4f) + “-“);
8: System.out.print(addCandy(1.9, (float)4) + “-“);
9: System.out.print(addCandy((long)(int)(short)2,(float)4)); } }
A. 4-6-6.0 B. 3-5-6 C. 3-6-6 D. 4-5-6 E. The code does not compile because of line 9. F. None of the above
F.
The code does not compile because line 3 contains a compilation error. The cast (int) is applied to fruit, not the expression fruit+vegetables. Since the cast operator has a higher operator precedence than the addition operator, it is applied to fruit, but the expression is promoted to a float, due to vegetables being float. The result cannot be returned as long in the add Candy() method without a cast. For this reason, option F is correct. If parentheses were added around fruit+vegetables, then the output would be 3-5-6, and option B would be correct.Remember that casting floating point numbers to integral values results in truncation, not rounding.
What is the output of the following code snippet?
int ph = 7, vis = 2;
boolean clear = vis > 1 & (vis < 9 || ph < 2);
boolean safe = (vis > 2) && (ph++ > 1);
boolean tasty = 7 <= –ph;
System.out.println(clear+”-“+safe+”-“+tasty);
A. true-true-true B. true-true-false C. true-false-true D. true-false-false E. false-true-true F. false-true-false G. false-false-true H. false-false-false
D. In the first boolean expression, v is is 2 and ph is 7, so this expression evaluates to true & (true || false), which reduces to true. The second boolean expression uses the short-circuitoperator, and since (vis > 2) is false, the right side is notevaluated, leaving ph at 7. In the last assignment, ph is 7, and thepre-decrement operator is applied first, reducing the expression to 7 <= 6 and resulting in an assignment of false. For thesereasons, option D is the correct answer.
What is the output of the following code snippet?
4: int pig = (short)4;
5: pig = pig++;
6: long goat = (int)2;
7: goat -= 1.0;
8: System.out.print(pig + “ - “ + goat);
A. 4 - 1 B. 4 - 2 C. 5 - 1 D. 5 - 2 E. The code does not compile due to line 7. F. None of the above
A. The code compiles and runs without issue, so option E is incorrect. Line 7 does not produce a compilation error since thecompound operator applies casting automatically. Line 5increments pig by 1, but it returns the original value of 4 since it isusing the post-increment operator. The pig variable is then assigned this value, and the increment operation is discarded.Line 7 just reduces the value of goat by 1, resulting in an output of4 - 1 and making option A the correct answer.
What are the unique outputs of the following code snippet?(Choose all that apply.)
int a = 2, b = 4, c = 2;
System.out.println(a > 2 ? –c : b++);
System.out.println(b = (a!=c ? a : b++));
System.out.println(a > b ? b < c ? b : 2 : 1);
A. 1 B. 2 C. 3 D. 4 E. 5 F. 6 G. The code does not compile
A, D, E. The code compiles without issue, so option G is incorrect.In the first expression, a > 2 is false, so b is incremented to 5 but since the post-increment operator is used, 4 is printed, makingoption D correct. The –c was not applied, because only one rightsize of the ternary expression was evaluated. In the second expression, a!=c is false since c was never modified. Since b is 5due to the previous line and the post-increment operator is used,b++ returns 5. The result is then assigned to b using the assignment operator, overriding the incremented value for b andprinting 5, making option E correct. In the last expression,parentheses are not required but lack of parentheses can make ternary expressions difficult to read. From the previous lines, a is2, b is 5, and c is 2. We can rewrite this expression withparentheses as (2 > 5 ? (5 < 2 ? 5 : 2) : 1). The secondternary expression is never evaluated since 2 > 5 is false, and theexpression returns 1, making option A correct
What are the unique outputs of the following code snippet?(Choose all that apply.)
short height = 1, weight = 3; short zebra = (byte) weight * (byte) height; double ox = 1 + height * 2 + weight; long giraffe = 1 + 9 % height + 1; System.out.println(zebra); System.out.println(ox); System.out.println(giraffe);
A. 1 B. 2 C. 3 D. 4 E. 5 F. 6 G. The code does not compile.
G. The code does not compile due to an error on the second line.Even though both height and weight are cast to byte, themultiplication operator automatically promotes them to int,resulting in an attempt to store an int in a short variable. For thisreason, the code does not compile, and option G is the onlycorrect answer. This line contains the only compilation error. Ifthe code were corrected to add parentheses around the entireexpression and cast it to a byte or short, then the program wouldprint 3, 6, and 2 in that order.
What is the output of the following code?
1: public class ArithmeticSample {
2: public static void main(String[] args) {
3: int sample1 = (2 * 4) % 3;
4: int sample2 = 3 * 2 % 3;
5: int sample3 = 5 * (1 % 2);
6: System.out.println(sample1+”-“+sample2+”-“+sample3);
7: }}
A. 0-0-5 B. 1-2-10 C. 2-1-5 D. 2-0-5 E. 3-1-10 F. 3-2-6 G. The code does not compile
D. First off, the * and % have the same operator precedence, so the expression is evaluated from left to right unless parentheses represent. The first expression evaluates to 8 % 3, which leaves remainder of 2. The second expression is just evaluated left tonight since * and % have the same operator precedence, and it reduces to 6 % 3, which is 0. The last expression reduces to 5 * 1,which is 5. Therefore, the output on line 6 is 2-0-5, making option D the correct answer.
The \_\_\_\_\_\_\_\_ operator increases a value and returns theoriginal value, while the \_\_\_\_\_\_\_\_ operator decreases a valueand returns the new value. A. post-increment, post-increment B. pre-decrement, post-decrement C. post-increment, post-increment D. post-increment, pre-decrement E. pre-increment, pre-decrement F. pre-increment, post-decrement
D. The pre- prefix indicates the operation is applied first, and the new value is returned, while the post- prefix indicates the original value is returned prior to the operation. Next, increment increases
the value, while decrement decreases the value. For these reasons,option D is the correct answer.