Programmer I Chapter 3: Operators Flashcards

1
Q

name 4 Numeric promotion rules

A
  1. If two values have different datatypes, Java will automatically promote one of the values to the larger of the two data types.
  2. 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.
  3. 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.
  4. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
What is the data type of x * y?
int x = 1;
long y = 33;
var z = x * y;
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
What is the data type of x + y?
double x = 39.21;
float y = 2.1;
var z = x + y;
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
What is the data type of x * y?
short x = 10;
short y = 3;
var z = x * y;
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
What is the data type of w * x / y?
short w = 14;
float x = 13;
double y = 30;
var z = w * x / y;
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

what lines compile?

float egg = 2.0 / 9;
int tadpole = (int)5 * 2L;
short frog = 3 - 2.0;

A

none of them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what line causes a compile error?

short mouse = 10;
short hamster = 3;
short capybara = mouse * hamster;

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

does this compile?

long goat = 10;
int sheep = 5;
sheep *= goat;

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

what will this print?

long wolf = 5;
long coyote = (wolf=3);
System.out.println(wolf);
System.out.println(coyote);

A

3
3

Assignment expressions are legal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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);

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

what is the output?

int rabbit = 6;
boolean bunny = (rabbit >= 6) || (++rabbit <= 7);
System.out.println(rabbit);

A

Because rabbit >= 6 is true, the increment operator on the right side of the expression is never evaluated, so the output is 6.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

what is the output?

int sheep = 1;int zzz = 1;
int sleep = zzz<10 ? sheep++ : zzz++;
System.out.print(sheep+”,”+zzz);

A

2,1

since the left-hand boolean expression was true, onlysheep was incremented

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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
A

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.

17
Q

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

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

18
Q

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
A

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.

19
Q

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
A

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.

20
Q

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

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.

21
Q

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

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

22
Q

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.
A

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.

23
Q

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
A

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.

24
Q
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
A

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.

25
Q

What is the output of the following code snippet?

boolean sunny = true, raining = false, sunday = true;
boolean goingToTheStore = sunny & raining ^ sunday;
boolean goingToTheZoo = sunday && !raining;
boolean stayingHome = !(goingToTheStore &&goingToTheZoo);
System.out.println(goingToTheStore + “-“ + goingToTheZoo+ “-“ +stayingHome);

A. true-false-false
B. false-true-false
C. true-true-true
D. false-true-true
E. false-false-false
F. true-true-false
G. None of the above
A

F. The first expression is evaluated from left to right since the operator precedence of & and ^ is the same, letting us reduce it to false ^ sunday, which is true, because sunday is true. In the second expression, we apply the negation operator, (!), first,reducing the expression to sunday && true, which evaluates to true. In the last expression, both variables are true so they reduce to !(true && true), which further reduces to !true, aka false. For these reasons, option F is the correct answer

26
Q

Which of the following statements are correct? (Choose all that apply.)

A. The return value of an assignment operation expression can be void.
B. The inequality operator (!=) can be used to compare objects.
C. The equality operator (==) can be used to compare a boolean value with a numeric value.
D. During runtime, the && and | operators may cause only the left side of the expression to be evaluated.
E. The return value of an assignment operation expression is the value of the newly assigned variable.
F. In Java, 0 and false may be used interchangeably.
G. The logical complement operator (!) cannot be used to flip numeric values.

A

B, E, G. The return value of an assignment operation in theexpression is the same as the value of the newly assigned variable.For this reason, option A is incorrect, and option E is correct.Option B is correct, and the equality (==) and inequality (!=)operators can both be used with objects. Option C is incorrect, as boolean and numeric types are not comparable with each other.For example, you can’t say true == 3 without a compilation error.Option D is incorrect, as only the short-circuit operator (&&) may cause only the left side of the expression to be evaluated. The (|)operator will cause both sides to be evaluated. Option F is incorrect, as Java does not accept numbers for boolean values.Finally, option G is correct, as you need to use the negation operator (-) to flip or negate numeric values, not the logical complement operator (!).

27
Q

Which operators take three operands or values? (Choose all that apply.)

A. =
B. &&
C. *=
D. ? :
E. &
F. ++
G. /
A

D. The ternary operator is the only operator that takes three values, making option D the only correct choice. Options A, B, C,E, and G are all binary operators. While they can be strung together in longer expressions, each operation uses only two values at a time. Option F is a unary operator and takes only one value

28
Q

How many lines of the following code contain compiler errors?

int note = 1 * 2 + (long)3;
short melody = (byte)(double)(note *= 2);
double song = melody;
float symphony = (float)((song == 1_000f) ? song * 2L :song);

A. 0
B. 1
C. 2
D. 3
E. 4
A

B. The first line contains a compilation error. The value 3 is cast to long. The 1 * 2 value is evaluated as int but promoted to long when added to the 3. Trying to store a long value in an invariable triggers a compiler error. The other lines do not contain any compilation errors, as they store smaller values in larger or
same-size data types, with the third and fourth lines using casting to do so

29
Q

Given the following code snippet, what is the value of the variables after it is executed? (Choose all that apply.)

int ticketsTaken = 1;
int ticketsSold = 3;
ticketsSold += 1 + ticketsTaken++;
ticketsTaken *= 2;
ticketsSold += (long)1;
A. ticketsSold is 8
B. ticketsTaken is 2
C. ticketsSold is 6
D. ticketsTaken is 6
E. ticketsSold is 7
F. ticketsTaken is 4
G. The code does not compile
A

C, F. The starting values of ticketsTaken and ticketsSold are 1and 3, respectively. After the first compound assignment,ticketsTaken is incremented to 2. The ticketsSold value isincreased from 3 to 5; since the post-increment operator was used the value of ticketsTaken++ returns 1. On the next line,ticketsTaken is doubled to 4. On the final line, ticketsSold is increased by 1 to 6. The final values of the variables are 4 and 6,for ticketsTaken and ticketsSold, respectively, making options C and F the correct answers. Note the last line does not trigger a compilation error as the compound operator automatically casts the right-hand operand

30
Q

Which of the following can be used to change the order of
operation in an expression? (Choose all that apply.)

A. [ ]
B. < >
C. ( )
D. \ /
E. { }
F. " "
A

C. Only parentheses, ( ), can be used to change the order of operation in an expression. The other operators, such as [ ], < >,and { }, cannot be used as parentheses in Java.

31
Q

What is the result of executing the following code snippet?(Choose all that apply.)

3: int start = 7;
4: int end = 4;
5: end += ++start;
6: start = (byte)(Byte.MAX_VALUE + 1);

A. start is 0
B. start is -128
C. start is 127
D. end is 8
E. end is 11
F. end is 12
G. The code does not compile.H. The code compiles but throws an exception at runtime.
A

B, F. The code compiles and runs successfully, so options G and Hare incorrect. On line 5, the pre-increment operator is executed first, so start is incremented to 8, and the new value is returned as the right side of the expression. The value of end is computed by adding 8 to the original value of 4, leaving a new value of 12 for end, and making option F a correct answer. On line 6, we are incrementing one past the maximum byte value. Due to overflow,this will result in a negative number, making option B the correct answer. Even if you didn’t know the maximum value of byte, you should have known the code compiles and runs and looked for the answer for start with a negative number

32
Q

Which of the following statements about unary operators are true? (Choose all that apply.)

A. Unary operators are always executed before any surrounding binary or ternary operators.
B. The - operator can be used to flip a boolean value.
C. The pre-increment operator (++) returns the value of the
variable before the increment is applied.
D. The post-decrement operator (–) returns the value of the variable before the decrement is applied.
E. The ! operator cannot be used on numeric values.
F. None of the above

A

A, D, E. Unary operators have the highest order of precedence,making option A correct. The negation operator (-) is used only for numeric values, while the logical complement operator (!) issued exclusively for boolean values. For these reasons, option B is incorrect, and option E is correct. Finally, the pre-increment/pre-decrement operators return the new value of the variable, while the post-increment/post-decrement operators return the original variable. For these reasons, option C is incorrect, and option D is
correct