Harsh Gupta
Harsh Gupta

Reputation: 73

Purpose of new keyword in creating array in Java

I want to know why an array created in Java static even when we use the new keyword to define it.

From what I've read, the new keyword allocates a memory space in the heap whenever it is encountered during run time, so why give the size of the array at all during definition.

e.g. Why can't

int[] array1=new int[20]; 

simply be:

int[] array1=new int[]; 

I know that it does not grow automatically and we have ArrayList for that but then what is the use of keyword new in this? It could have been defined as int array1[20]; like we used to do it in C, C++ if it has to be static.

P.S. I know this is an amateurish question but I am an amateur, I tried to Google but couldn't find anything comprehensive.

Upvotes: 3

Views: 5423

Answers (6)

Tom Tsagkatos
Tom Tsagkatos

Reputation: 1494

Well, in Java everything is an object, including arrays (they have length and other data). Thats why you cannot use

int myArray[20]; 

In java that would be an int and the compiler would be confused. Instead by using this:

int[] myArray;

You are declaring that myArray is of type int[] (int array) so Java understands it.

Also in java the length of the array and other data are saved on the array, for this reason you don't have to declare size of array during declaration, instead when creating an array (using new) the data are saved.

Maybe there is a better reason that oracle may have answered already, but the fact that in Java everything is an object must have something to do with it. Java is quite specific about objects and types, unlike C where you have more freedom but everything is more loose (especially using pointers).

Upvotes: 3

villasv
villasv

Reputation: 6841

My understanding of OP's reasoning is:

new is used for allocating dynamic objects (which can grow like, ArrayList), but arrays are static (can't grow). So one of them is unnecessary: the new or the size of the array.

If that is the question, then the answer is simple:

Well, in Java new is necessary for every Object allocation, because in Java all objects are dynamically allocated.

Turns out that in Java, arrays are objects, different from C/C++ where they are not.

Upvotes: 1

zapl
zapl

Reputation: 63955

All of Java's variables are at most a single 64bit field. Either primitives like

  • integer (32bit)
  • long (64bit)
  • ...

or references to Objects which depending on JVM / config / OS are 64 or 32 bit fields (but unlike 64bit primitives with atomicity guaranteed).

There is no such thing as C's int[20] "type". Neither is there C's static.

What int[] array = new int[20] boils down to is roughly

int* array = malloc(20 * sizeof(java_int))

Each time you see new in Java you can imagine a malloc and a call to the constructor method in case it's a real Object (not just an array). Each Object is more or less just a struct of a few primitives and more pointers.

The result is a giant network of relatively small structs pointing to other things. And the garbage collector's task is to free all the leaves that have fallen off the network.

And this is also the reason why you can say Java is copy by value: both primitives and pointers are always copied.

regarding static in Java: there is conceptually a struct per class that represents the static context of a class. That's the place where static instance variables are anchored. Non-static instance variables are anchored at with their own instance-struct

class Car {
    static int[] forAllCars = new int[20];
    Object perCar;
}
...
new Car();

translates very loosely (my C is terrible) to

struct Car-Static {
    Object* forAllCars;
};
struct Car-Instance {
    Object* perCar;
};
// .. class load time. Happens once and this is referenced from some root object so it can't get garbage collected
struct Car-Static *car_class = (struct Car-Static*) malloc(sizeof(Car-Static));
car_class->forAllCars = malloc(20 * 4);

// .. for every new Car();
struct Car-Instance *new_reference = (struct Car-Instance*) malloc(sizeof(Car-Instance));
new_reference.perCar = NULL; // all things get 0'd
new_reference->constructor();
// "new" essentially returns the "new_reference" then

Upvotes: 0

Mike Nakis
Mike Nakis

Reputation: 62025

This may be an amateurish question, but it is one of the best amateurish questions you could make.

In order for java to allow you to declare arrays without new, it would have to support an additional kind of data type, which would behave like a primitive in the sense that it would not require allocation, but it would be very much unlike a primitive in the sense that it would be of variable size. That would have immensely complicated the compiler and the JVM.

The approach taken by java is to provide the bare minimum and sufficient primitives in order to be able to get most things done efficiently, and let everything else be done using objects. That's why arrays are objects.

Also, you might be a bit confused about the meaning of "static" here. In C, "static" means "of file scope", that is, not visible by other object files. In C++ and in Java, "static" means "belongs to the class" rather than "belongs to instances of the class". So, the term "static" is not suitable for describing array allocation. "Fixed size" or "fixed, predefined size" would be more suitable terms.

Upvotes: 4

pwilmot
pwilmot

Reputation: 596

Since arrays are fixed-size they need to know how much memory to allocate at the time they are instantiated.

ArrayLists or other resizing data structures that internally use arrays to store data actually re-allocate larger arrays when their inner array data structure fills up.

Upvotes: 1

Andremoniy
Andremoniy

Reputation: 34900

The main idea of the array data structure is that all its elements are located in the sequential row of memory cells. That is why you can not create array with variable size: it should be unbounbed space vector in memory for this purpose, which is impossible.

If you want change size of array, you should recreate it.

Upvotes: 1

Related Questions