0
0
Javaprogramming~20 mins

Type casting in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Type Casting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
    }
}
A130
B0
C-126
DCompilation error
Attempts:
2 left
💡 Hint
Remember that byte can only hold values from -128 to 127, so casting int to byte may cause overflow.
Predict Output
intermediate
2: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);
    }
}
A9
BCompilation error
C9.99
D10
Attempts:
2 left
💡 Hint
Casting from double to int truncates the decimal part.
Predict Output
advanced
2: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);
    }
}
A100
B-116
CCompilation error
D90
Attempts:
2 left
💡 Hint
Arithmetic operations on bytes are promoted to int, so explicit cast is needed.
Predict Output
advanced
2: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);
    }
}
AClassCastException at runtime
Bnull
CCompilation error
DHello
Attempts:
2 left
💡 Hint
Casting an object to an incompatible type causes runtime error.
🧠 Conceptual
expert
3: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);
    }
}
A4
B3
C5
D6
Attempts:
2 left
💡 Hint
Count only elements that are Number instances and have intValue() > 3.