JAVA OCA ‎1Z0-808 Chapter 2 - Operators and Statements

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

2 The multiplication and % have the same operator precedence, so the expression is evaluated from left-to-right. The result of 5 * 4 is 20, and 20 % 3 is 2 (20 divided by 3 is 18, the remainder is 2).

1: public class ArithmeticSample { 2: public static void main(String[] args) { 3: int x = 5 * 4 % 3; 4: System.out.println(x); 5: }}

The code will not compile because of line 5. . In this example, the ternary operator has two expressions, one of them a String and the other a boolean value. The ternary operator is permitted to have expressions that don't have matching types, but the key here is the assignment to the String reference. The compiler knows how to assign the first expression value as a String, but the second boolean expression cannot be set as a String; therefore, this line will not compile.

1: public class CompareValues { 2: public static void main(String[] args) { 3: int x = 0; 4: while(x++ < 10) {} 5: String message = x > 10 ? "Greater than" : false; 6: System.out.println(message+","+x); 7: } 8: }

8 As you learned in the section "Ternary Operator," although parentheses are not required, they do greatly increase code readability, such as the following equivalent statement: System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7) We apply the outside ternary operator fi rst, as it is possible the inner ternary expression may never be evaluated. Since (x>2) is true, this reduces the problem to: System.out.println((x < 4) ? 10 : 8) Since x is greater than 2, the answer is 8.

1: public class TernaryTester { 2: public static void main(String[] args) { 3: int x = 5; 4: System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); 5: }}

11 The code compiles without issue, so option F is incorrect. After the first execution of the loop, i is decremented to 9 and result to 13. Since i is not 8, keepGoing is false, and the loop continues. On the next iteration, i is decremented to 8 and result to 11. On the second execution, i does equal 8, so keepGoing is set to false. At the conclusion of the loop, the loop terminates since keepGoing is no longer true. The value of result is 11.

3: boolean keepGoing = true; 4: int result = 15, i = 10; 5: do { 6: i--; 7: if(i==8) keepGoing = false; 8: result -= 2; 9: } while(keepGoing); 10: System.out.println(result);

true, 20, false This example is tricky because of the second assignment operator embedded in line 5. The expression (z=false) assigns the value false to z and returns false for the entire expression. Since y does not equal 10, the left-hand side returns true; therefore, the exclusive or (^) of the entire expression assigned to x is true. The output reflects these assignments, with no change to y, so option B is the only correct answer. The code compiles and runs without issue, so option F is not correct.

3: boolean x = true, z = true; 4: int y = 20; 5: x = (y != 10) ^ (z=false); 6: System.out.println(x+", "+y+", "+z);

The code will not compile because of line 4. Line 4 generates a possible loss of precision compiler error. The cast operator has the highest precedence, so it is evaluated first, casting a to a byte. Then, the addition is evaluated, causing both a and b to be promoted to int values. The value 90 is an int and cannot be assigned to the byte sum without an explicit cast, so the code does not compile. The code could be corrected with parentheses around (a + b), in which case 90 would be the correct answer.

3: byte a = 40, b = 50; 4: byte sum = (byte) a + b; 5: System.out.println(sum);

The variable y is declared within the body of the do-while statement, so it is out of scope on line 6. Line 6 generates a compiler error.

3: do { 4: int y = 1; 5: System.out.print(y++ + " "); 6: } while(y <= 10);

greatgood The value of grade is 'B' and there is a matching case statement that will cause "great" to be printed. There is no break statement after the case, though, so the next case statement will be reached, and "good" will be printed. There is a break after this case statement, though, so the switch statement will end.

3: final char a = 'A', d = 'D'; 4: char grade = 'B'; 5: switch(grade) { 6: case a: 7: case 'B': System.out.print("great"); 8: case 'C': System.out.print("good"); break; 9: case d: 10: case 'F': System.out.print("not good"); 11: }

12 The code compiles successfully, so option F is incorrect. On line 5, the pre-increment operator is used, so c is incremented to 4 and the new value is returned to the expression. The value of result is computed by adding 4 to the original value of 8, resulting in a new value of 12, which is output on line 6.

3: int c = 7; 4: int result = 4; 5: result += ++c; 6: System.out.println(result);

2 The expression on line 5 is true when row * col is an even number. On the first iteration, row = 1 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 1. On the second iteration, row = 1 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line 6 is true and the continue ends the outer loop with count still at 1. On the fourth iteration, row = 3 and col = 1, so the expression on line 6 is false, the continue is skipped, and count is incremented to 2. Finally, on the fifth and final iteration, row = 3 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with count still at 2. The result of 2 is displayed.

3: int count = 0; 4: ROW_LOOP: for(int row = 1; row <=3; row++) 5: for(int col = 1; col <=2 ; col++) { 6: if(row * col % 2 == 0) continue ROW_LOOP; 7: count++; 8: } 9: System.out.println(count);

36 Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first loop, m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 = 11. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum of the new values for m + n, 11 + 12 = 23. After the iteration of the third loop, m is updated to 6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On the fourth iteration of the loop, m > n evaluates to false, as 6 < 7 is not true. The loop ends and the most recent value of x, 36, is output.

3: int m = 9, n = 1, x = 0; 4: while(m > n) { 5: m--; 6: n += 2; 7: x += m + n; 8: } 9: System.out.println(x);

The code will not compile because of line 5. The variable x is an int and s is a reference to a String object. The two data types are incomparable because neither variable can be converted to the other variable's type. The compiler error occurs on line 5 when the comparison is attempted.

3: int x = 0; 4: String s = null; 5: if(x == s) System.out.println("Success"); 6: else System.out.println("Failure");

The code will not compile because of line 4. This is actually a much simpler problem than it appears to be. The while statement on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the output would be 10, 6.

3: int x = 1, y = 15; 4: while x < 10 5: y--; 6: x++; 7: System.out.println(x+", "+y);

The code will not compile because of line 7 .The code does not compile because two else statements cannot be chained together without additional if-then statements. Line 6 by itself does not cause a problem, only when it is paired with Line 7. One way to fix this code so it compiles would be to add an if-then statement on line 6. The other solution would be to remove line 7.

3: int x = 4; 4: long y = x * 4 - x++; 5: if(y<10) System.out.println("Too Low"); 6: else System.out.println("Just right"); 7: else System.out.println("Too High");

Success The value of b after line 4 is false. However, the if-then statement on line 5 contains an assignment, not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success.

3: int x1 = 50, x2 = 75; 4: boolean b = x1 >= x2; 5: if(b = true) System.out.println("Success"); 6: else System.out.println("Failure");

10,

3: java.util.List <Integer>list = new java.util.ArrayList<Integer>(); 4: list.add(10); , 5: list.add(14); 6: for(int x : list) { 7: System.out.print(x + ", "); 8: break; 9: }

■ int and Integer ■ byte and Byte ■ short and Short ■ char and Character ■ int and Integer ■ String ■ enum values For the exam, we recommend you memorize this list. Note that boolean and long, and their associated wrapper classes, are not supported by switch statements

Data types supported by switch statements.

■ AND is only true if both operands are true. ■ Inclusive OR is only false if both operands are false. ■ Exclusive OR is only true if the operands are different.

Explain. x && y, x || y, x ^^ y

The code contains an infinite loop and does not terminate. In this example, the update statement of the for loop is missing, which is fine as the statement is optional. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over and over again because i remains 0 after every iteration of the loop.

How many times will the following code print "Hello World"? 3: for(int i=0; i<10 ; ) { 4: i = i++; 5: System.out.println("Hello World"); 6: }

1. If two values have different data types, 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.

Numeric Promotion Rules.

B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x is automatically promoted to long and cannot be automatically stored in y, 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 data type. Option F solves the problem by increasing the data type of the assignment so that long is allowed.

What change would allow the following code snippet to compile? (Choose all that apply) 3: long x = 10; 4: int y = 2 * x; A. No change; it compiles as is. B. Cast x on line 4 to int. C. Change the data type of x on line 3 to short. D. Cast 2 * x on line 4 to int. E. Change the data type of y on line 4 to short. F. Change the data type of y on line 4 to long.

A, B, D. The value x + y is automatically promoted to int, so int and data types that can be promoted automatically from int will work. Options A, B, D are such data types. Option C will not work because boolean is not a numeric data type. Options E and F will not work without an explicit cast to a smaller data type.

What data type (or types) will allow the following code snippet to compile? (Choose all that apply) byte x = 5; byte y = 10; _____ z = x + y; A. int B. long C. boolean D. double E. short F. byte

This is actually a trick question, as this code will not compile! As you may remember from Chapter 1, fl oating-point literals are assumed to be double, unless postfi xed with an f, as in 2.1f. If the value was set properly to 2.1f, then the promotion would be similar to the last 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? double x = 39.21; float y = 2.1;

A, D. Option A is the equality operator and can be used on numeric primitives, boolean values, and object references. Options B and C are both arithmetic operators and cannot be applied to a boolean value. Option D is the logical complement operator and is used exclusively with boolean values. Option E is the modulus operator, which can only be used with numeric primitives. Finally, option F is a relational operator that compares the values of two numbers.

Which of the following Java operators can be used with boolean variables? (Choose all that apply) A. == B. + C. -- D. ! E. % F. <=

no The fi rst statement does not compile because you are trying to assign a double 1.0 to an integer value. Even though the value is a mathematic integer, by adding .0, you're instructing the compiler to treat it as a double. The second statement does not compile because the literal value 1921222 is outside the range of short and the compiler detects this. The third statement does not compile because of the f added to the end of the number that instructs the compiler to treat the number as fl oating-point value. Finally, the last statement does not compile because Java interprets the literal as an int and notices that the value is larger than int allows. The literal would need a postfi x L to be considered a long.

Will these compile? int x = 1.0; short y = 1921222; int z = 9f; long t = 19230139819381032

The code will not compile. The variables in the initialization block must all be of the same type. In the fi rst example, y and z were both long, so the code compiled without issue, but in this example they have differing types, so the code will not compile.

for(long y = 0, int x = 4; x < 5 && y<10; x++, y++) { System.out.print(x + " "); }

The code won't compile. If you notice, x is defi ned in the initialization block of the loop, and then used after the loop terminates. Since x was only scoped for the loop, using it outside the loop will throw a compiler error.

for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(y + " "); } System.out.print(x);

The code will not compile. it does not compile because of the initialization block. The difference is that x is repeated in the initialization block after already being declared before the loop, resulting in the compiler stopping because of a duplicate variable declaration. We can fi x this loop by changing the declaration of x and y as follows: int x = 0; long y = 10; for(y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(x + " "); }

int x = 0; for(long y = 0, x = 4; x < 5 && y < 10; x++, y++) { System.out.print(x + " "); }

This code demonstrates three variations of the for loop you may not have seen. First, you can declare a variable, such as x in this example, before the loop begins and use it after it completes. Second, your initialization block, boolean expression, and update statements can include extra variables that may not reference each other. For example, z is defi ned in the initialization block and is never used. Finally, the update statement can modify multiple variables. This code will print the following when executed: 0 1 2 3 4

int x = 0; for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) { System.out.print(y + " "); } System.out.print(x);

3 0 The first time this loop executes, the inner loop repeats until the value of x is 4. The value will then be decremented to 3 and that will be the output at the end of the first iteration of the outer loop. On the second iteration of the outer loop, the inner do-while will be executed once, even though x is already not greater than 5. As you may recall, do-while statements always execute the body at least once. This will reduce the value to 1, which will be further lowered by the decrement operator in the outer loop to 0. Once the value reaches 0, the outer loop will terminate. The result is that the code will output the following: 3 0

int x = 20; while(x>0) { do { x -= 2 } while (x>5); x--; System.out.print(x+"\t"); }

x is 2 y is 7 This one is more complicated than the previous example because x is modifi ed three times on the same line. Each time it is modifi ed, as the expression moves from left to right, the value of x changes, with different values being assigned to the variable. As you'll recall from our discussion on operator precedence, order of operation plays an important part in evaluating this example. So how do you read this code? First, the x is incremented and returned to the expression, which is multiplied by 5. We can simplify this: int y = 4 * 5 / x-- + --x; // x assigned value of 4 Next, x is decremented, but the original value of 4 is used in the expression, leading to this: int y = 4 * 5 / 4 + --x; // x assigned value of 3 The fi nal assignment of x reduces the value to 2, and since this is a pre-increment operator, that value is returned to the expression: int y = 4 * 5 / 4 + 2; // x assigned value of 2 Finally, we evaluate the multiple and division from left-to-right, and fi nish with the addition. The result is then printed: x is 2 y is 7

int x = 3; int y = ++x * 5 / x-- + --x; System.out.println("x is " + x); System.out.println("y is " + y);

Notice that we intentionally mix a for and for-each loop in this example. The outer loops will execute a total of three times. Each time the outer loop executes, the inner loop is executed four times. When we execute this code, we see the following output: 5 2 1 3 3 9 8 9 5 7 12 7

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}}; for(int[] mySimpleArray : myComplexArray) { for(int i=0; i < mySimpleArray.length; i++) { System.out.print(mySimpleArray[i]+"\t"); } System.out.println(); }

3 3 The key here is that (x=3) does two things. First, it sets the value of the variable x to be 3. Second, it returns a value of the assignment, which is also 3. The exam creators are fond of inserting the assignment operator = in the middle of an expression and using the value of the assignment as part of a more complex expression.

long x = 5; long y = (x=3); System.out.println(x); System.out.println(y);

Based on everything you have learned up until now, can you understand why the last line of this statement will not compile? If you remember, short values are automatically promoted to int when applying any arithmetic operator, with the resulting value being of type int. Trying to set a short variable to an int results in a compiler error, as Java thinks you are trying to implicitly convert from a larger data type to a smaller one. There are times that you may want to override the default behavior of the compiler. For example, in the preceding example, we know the result of 10 * 3 is 30, which can easily fi t into a short variable. If you need the result to be a short, though, you can override this behavior by casting the result of the multiplication: short x = 10; short y = 3; short z = (short)(x * y); By performing this explicit cast of a larger value into a smaller data type, you are instructing the compiler to ignore its default behavior. In other words, you are telling the compiler that you have taken additional steps to prevent overfl ow or underfl ow. It is also possible that in your particular application and scenario, overfl ow or underfl ow would result in acceptable values.

short x = 10; short y = 3; short z = x * y;


संबंधित स्टडी सेट्स

Digital Cloud Leader - Module Questions

View Set

DELEGATION, LEADERSHIP. MANAGE,ENT

View Set

Test #1 Microeconomics (ch. 3 only)

View Set

Chapter 33: Management of Patients With Nonmalignant Hematologic Disorders

View Set

Module 5: Ch 11 More on Experiments

View Set