Challenge - 5 Problems
Type Casting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of implicit and explicit casting
What is the output of the following Java code?
Java
public class Main { public static void main(String[] args) { int a = 130; byte b = (byte) a; System.out.println(b); } }
Attempts:
2 left
💡 Hint
Remember that byte can only hold values from -128 to 127, so casting int to byte may cause overflow.
✗ Incorrect
The int value 130 is cast to byte. Since byte ranges from -128 to 127, 130 overflows and wraps around to -126.
❓ Predict Output
intermediate2:00remaining
Casting double to int and output
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { double d = 9.99; int i = (int) d; System.out.println(i); } }
Attempts:
2 left
💡 Hint
Casting from double to int truncates the decimal part.
✗ Incorrect
Casting double 9.99 to int removes the decimal part, resulting in 9.
❓ Predict Output
advanced2:00remaining
Output of casting with arithmetic expressions
What is the output of this Java program?
Java
public class Main { public static void main(String[] args) { byte b1 = 40; byte b2 = 50; byte b3 = (byte) (b1 + b2); System.out.println(b3); } }
Attempts:
2 left
💡 Hint
Arithmetic operations on bytes are promoted to int, so explicit cast is needed.
✗ Incorrect
b1 + b2 is promoted to int 90, then cast back to byte 90, which fits in byte range.
❓ Predict Output
advanced2:00remaining
Casting objects and ClassCastException
What happens when you run this Java code?
Java
public class Main { public static void main(String[] args) { Object obj = "Hello"; Integer num = (Integer) obj; System.out.println(num); } }
Attempts:
2 left
💡 Hint
Casting an object to an incompatible type causes runtime error.
✗ Incorrect
The object holds a String, but is cast to Integer, causing ClassCastException at runtime.
🧠 Conceptual
expert3:00remaining
Number of elements after casting and filtering
Consider this Java code snippet. How many elements are in the resulting array after casting and filtering?
Java
import java.util.Arrays; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { Object[] arr = {1, 2.5, 3, 4.0f, 5L, "6", 7}; int[] result = Arrays.stream(arr) .filter(o -> o instanceof Number) .mapToInt(o -> ((Number) o).intValue()) .filter(i -> i > 3) .toArray(); System.out.println(result.length); } }
Attempts:
2 left
💡 Hint
Count only elements that are Number instances and have intValue() > 3.
✗ Incorrect
Numbers are 1,2.5,3,4.0f,5L,7 ("6" is String). Their int values: 1,2,3,4,5,7. Filter >3 gives 4,5,7 → 3 elements.