Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "Object[] object = new String[][]" compiles? - Java

Tags:

java

arrays

Why does this code compile?

Object[] object = new String[5][5];

I mean, why can I do that if I'm creating an array object with different dimensions than specified in the reference variable?

This doesn't compile:

String[] strings = new String[5][5];

So what is happening here?

like image 554
GabrielBB Avatar asked Jan 03 '14 00:01

GabrielBB


People also ask

What does new String [] do in Java?

By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.

Is object and string same?

String objects have the feature of adding a property to an object. In general, the string(with a small 's') denotes a primitive whereas String(with an uppercase 'S') denotes an object. JavaScript supports five types of primitives and string is one of them.


1 Answers

The first one compiles because String[] is an Object. The 2nd one doesn't compiles because String is not String[].

Object[] object = new String[5][5];  // Means each element is an String[] which is an Object as well.

String[] strings = new String[5][5]; // Also Means each element is an String[] which is not same as just String.
like image 187
fastcodejava Avatar answered Sep 20 '22 23:09

fastcodejava