Consider the following Java code snippet:
int result = 3 + 4 * 2 / (1 - 5) % 2;
What is the value of result after this code runs?
int result = 3 + 4 * 2 / (1 - 5) % 2; System.out.println(result);
Remember the order: parentheses, multiplication/division/modulus, then addition/subtraction.
Step by step:
Parentheses: (1 - 5) = -4
4 * 2 = 8
8 / -4 = -2 (integer division)
-2 % 2 = 0
3 + 0 = 3
Given the code:
int a = 5; // binary 0101 int b = 3; // binary 0011 boolean result = a > 2 && b < 5 | a == 5;
What is the value of result?
int a = 5; int b = 3; boolean result = a > 2 && b < 5 | a == 5; System.out.println(result);
Check operator precedence between && and | in Java.
Operator precedence: && has higher precedence than | (bitwise OR).
So expression is evaluated as: (a > 2 && b < 5) | a == 5
a > 2: true (5>2)
b < 5: true (3<5)
a == 5: true
true && true = true
true | true = true
Examine this code snippet:
int x = 10; int y = 20; boolean check = x < y && x++ > 5 || y-- < 15;
What error or output does this code produce?
int x = 10; int y = 20; boolean check = x < y && x++ > 5 || y-- < 15; System.out.println(check); System.out.println(x); System.out.println(y);
Remember the order of evaluation and side effects of post-increment and post-decrement.
Operator precedence: && higher than ||.
Expression: (x < y && x++ > 5) || (y-- < 15)
x=10, y=20
x < y: true
x++ > 5: post-increment uses 10 > 5 (true), then x=11
true && true = true
|| short-circuits (left true), so y-- not evaluated, y=20
Output: true, 11, 20
Which of the following Java code snippets will cause a syntax error?
Look for invalid operator combinations.
Option D has 5 + * 3 which is invalid syntax.
Options A, B, and C are valid arithmetic expressions.
Consider this Java code:
int[] arr = {1, 2, 3, 4, 5};
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i]++ * --arr[i];
}How many elements in result are greater than 0 after this loop?
int[] arr = {1, 2, 3, 4, 5}; int[] result = new int[arr.length]; for (int i = 0; i < arr.length; i++) { result[i] = arr[i]++ * --arr[i]; } int count = 0; for (int val : result) { if (val > 0) count++; } System.out.println(count);
Understand how post-increment and pre-decrement affect the value used in multiplication.
For each i, arr[i]++ * --arr[i]:
- arr[i]++: uses original n, then arr[i] = n+1
- --arr[i]: arr[i] = n, uses n
- n * n = n² > 0 for all original values 1-5
Operations cancel out per element, result = [1,4,9,16,25], all >0, count=5