Java Tricky Question: Why Does Storing 42 Into This Array Compile Fine but Crash at Runtime?

java dev.to

Here is a scenario that surprises people in interviews and in real code. Look at this tiny program and guess what happens when it runs. public class ArrayCovariance { public static void main(String[] args) { Object[] arr = new String[1]; arr[0] = 42; } } Four popular guesses: It does not compile. You cannot put an Integer where Strings live. It compiles and runs fine. arr is an Object[], and everything is an Object. It crashes with a ClassCastException. It cras

Read Full Tutorial open_in_new
arrow_back Back to Tutorials