Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does array class work in Java?

Tags:

java

arrays

jvm

In Java, array is a class and extends Object. I am curious to know about this special array class. I don't find the class definition anywhere. Doing a getClass().getName() gives strange result.

String[] array = new String[]{"one","two"};
System.out.println(array.getClass().getName()); // prints [Ljava.lang.String;

I want to understand how array works under the hood. Is the array class definition hardcoded in the JVM?

Any resources, books, links on this will be helpful.

Thank you.

like image 470
oks16 Avatar asked May 26 '10 07:05

oks16


People also ask

How does array work in Java?

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

What is an array class in Java?

The Arrays class in java. util package is a part of the Java Collection Framework. This class provides static methods to dynamically create and access Java arrays. It consists of only static methods and the methods of Object class. The methods of this class can be used by the class name itself.

How does an array work?

Arrays are extremely powerful data structures that store elements of the same type. The type of elements and the size of the array are fixed and defined when you create it. Memory is allocated immediately after the array is created and it's empty until you assign the values.


1 Answers

Yes, basically arrays are something the VM knows about intimately, like the primitive types. There are specific bytecode instructions to work with arrays - creating them, indexing into them etc.

As for resources to find out more - the JVM specification is probably the best starting point. Section 7.9 has some examples of bytecode working with arrays.

like image 52
Jon Skeet Avatar answered Oct 15 '22 21:10

Jon Skeet