-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
  • 27,810
  • 13
  • 101
  • 139
abc123
  • 129
  • 2
  • 10
  • 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 – abc123 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
  • 81,660
  • 23
  • 145
  • 268
-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
  • 305,947
  • 44
  • 307
  • 483
  • 1
    It will not fail to compile. Answer is incorrect. And no explanation is provided. – user207421 Apr 17 '22 at 03:43
  • Sorry, the code will not fail to compile, Arrays are objects as well, and since "obj" is declared as an Object then the code will compile without issues. You could declare Arrays of primitive, string, or anything else, they are considered as Object. – ThierryKas Jan 18 '23 at 04:01