Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the class of int array? [duplicate]

Tags:

java

object

class

Problem1: I have a doubt that if we can only create objects of class then how are we able to create objects of primitive data types such as int,char etc.

Problem2: Now suppose Ankit is a class and if I write

Ankit a=new Ankit();
System.out.println(a.getClass().getName());

it will give me class name of a. Also if I write

System.out.println(Ankit.class);

Then too it will give class name.But If I write

int ar[]=new int[10];
System.out.println(ar.getClass().getName());
System.out.println(int.class); 

then I get output as:

[I and int

Why so? Here also I should get same output as class name of int ar then why different outputs and what is [I?

like image 951
Ankit Srivastava Avatar asked Sep 18 '25 22:09

Ankit Srivastava


1 Answers

Your second snippet does not do the same as your first snippet. Instead, you're printing

  1. The class name of an int array
  2. The class name of a primitive int

You should change the last line of your snippet to:

System.out.println(int[].class); 

to make it print the same thing as the line above.

About the second part of your question: that's just how java represents class name for arrays.

  • A one-dimensional array of int is [I
  • A two-dimensional array of int is [[I
  • A one-dimensional array of your class Ankit is [LAnkit; (which you can observe with System.out.println(Ankit[].class);)
like image 197
Erwin Bolwidt Avatar answered Sep 20 '25 12:09

Erwin Bolwidt