-3

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.

E_net4 - Krabbe mit Hüten
  • 24,143
  • 12
  • 85
  • 121
Anil
  • 99
  • 1
  • 9
  • 2
    All arrays are instances of `Object`. Any kind of object can be assigned to an `Object` reference. – Andy Turner Oct 01 '21 at 15:32
  • 2
    "int is clearly a primitive variable" yes, but this isn't an `int`, it's an `int[][]`, which is a reference type. But you can write `Object obj = 0;` anyway, because of autoboxing. – Andy Turner Oct 01 '21 at 15:35
  • Similar to question: https://stackoverflow.com/questions/2267790/how-are-arrays-implemented-in-java – Ofir Oct 01 '21 at 15:35
  • 1
    Think of it in a way - anything that needs `new` for creating an instance is an `Object` – Vasily Liaskovsky Oct 01 '21 at 15:35
  • 1
    Understood, when ever new is Used that means I am working on an Object and "int[][], which is a reference type." thanks guys! I had mentioned to mention the reason for downvoting if some body plans on doing that but still somebody down voted without mentioning any reason. Anyways thanks @AndyTurner and Vasily – Anil Oct 01 '21 at 16:59

2 Answers2

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.

Code-Apprentice
  • 76,639
  • 19
  • 130
  • 241
-1

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.

user207421
  • 298,294
  • 41
  • 291
  • 462