Why I am not able to assign string or any other values to the images array?.
The Java type system prevents it. An array declared with type Image[]
can only hold objects that are Image
instances, or instances of a subtype of Image
(or null
values). The compiler will prevent you from doing that.
That is what is meant when we say that Java is a staticly typed language.
Furthermore, the runtime system is designed so to make it impossible to “break” the static typing rules for arrays. For example, if you try to use reflection to put a String
into a an Image[]
, you will get an immediate exception.
That is what is meant when we say that Java is a strongly typed language.
(There are some issues to do with generic types and unsafe conversions, but even if you get that wrong the worst that can happen is that some of the hidden typecasts may result in exceptions in unexpected places.)
(The only way to actually break the type system is to step outside of the Java language; e.g. by using native code or the Unsafe
class. But if you do that you are liable to make the JVM unstable, leading to JVM panics.)
In case of
String [] names = new String[3]
, the names array can hold string values. So, is there anything in the String class which will allow only string to assign to names array and we cannot assign any object to names array?
Sure. The type system. The situation is the same as for your example with Image
arrays.
But note that it is not the String
class that is doing this … except that String
is a final
class, so no subtypes of String
are possible.
solved what decides whether an array can hold objects or not in Java