SCJP Java Operators, Type Casting, and Assignments — Questions and Answers
Question 1: What is the result of the expression `6 & 3` in Java?
- 7
- 5
- 2 (Correct answer)
- 9
Correct answer: 2
The & operator performs a bitwise AND. 6 in binary is 110 and 3 is 011. ANDing each bit: 110 & 011 = 010, which equals 2.
Question 2: What is the value of `byte b = (byte) 130;` in Java?
- 130
- -126 (Correct answer)
- 127
- Compilation error
Correct answer: -126
byte holds values from -128 to 127. 130 in binary (8 bits) is 10000010. With a signed byte, the leading 1 indicates a negative number. Using two's complement, this equals -126.
Question 3: What does the compound assignment `x += 1.5;` do when x is declared as `int x = 3;`?
- Causes a compile-time error due to loss of precision
- Assigns 4.5 to x
- Assigns 4 to x after an implicit narrowing cast (Correct answer)
- Assigns 5 to x by rounding up
Correct answer: Assigns 4 to x after an implicit narrowing cast
Compound assignment operators include an implicit narrowing cast. `x += 1.5` is equivalent to `x = (int)(x + 1.5)`, so 3 + 1.5 = 4.5 is truncated to 4. A plain `x = x + 1.5` would fail to compile.
Question 4: What is the output of `System.out.println(1 + 2 + "3" + 4 + 5);`?
- 12345
- 33 + 45
- 3345 (Correct answer)
- 15
Correct answer: 3345
Evaluation is left-to-right. `1 + 2` = 3 (int addition), then `3 + "3"` = "33" (string concatenation), then "33" + 4 = "334", then "334" + 5 = "3345".
Question 5: What is the result of `System.out.println(5 >> 1);`?
- 10
- 2 (Correct answer)
- 3
- 1
Correct answer: 2
The >> operator is the signed right-shift. Shifting 5 (binary 101) right by 1 position gives 010, which is 2. Each right-shift by 1 is equivalent to integer division by 2.
Question 6: Which assignment causes a compile-time error?
- long l = 100;
- float f = 100L;
- int i = 'A';
- byte b = 100L; (Correct answer)
Correct answer: byte b = 100L;
Assigning a long literal to a byte requires an explicit cast because it is a narrowing conversion. long→byte cannot be done implicitly. The other assignments are widening conversions (int→long, long→float) or a char-to-int widening, all of which are implicit.
What is the result of the expression `6 & 3` in Java?