'How can an object reference in java hold the reference to a primitive double dimensional int array [duplicate]
I have a piece of code-
public class Sudoku {
static int[][] game;
public static void main(String[] args) {
int [][] games= new int[3][3];
Object obj =games;
}
}
My question here is how can the "games" reference variable be assigned to the reference variable of type "Object"? I thought the "ClassCastException" would be thrown at runtime. But the code compiles and runs fine. Isnt the reference variable "games" incompatible to be assigned to an Object reference because of 2 reasons- 1)"games" is the reference to a double dimensional int array, whereas "obj" is the reference to an Object. 2)int is clearly a primitive variable..how can it be assigned to a variable of type object? I am running this in the Intellij IDE.
Solution 1:[1]
Isnt the reference variable "games" incompatible to be assigned to an Object reference because of 2 reasons- 1)"games" is the reference to a double dimensional int array, whereas "obj" is the reference to an Object. 2)int is clearly a primitive variable
You are correct that int
is a primitive type. However, the type of games
in your example is int[][]
, not int
, and is a subclass of Object
.
Solution 2:[2]
if your code were
int [] games= new int[3];
Object obj =games; // will fail to compile,
but declare game
as int [][] games
can be assigned to obj
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Code-Apprentice |
Solution 2 | user207421 |