whereas in java objects' creation occur in heap , As a result of this action objects has a dynamic capacity in java.in this level I have an ambiguity that why arrays capacity in Java should be listed at the time of their initialization? thanks.
Asked
Active
Viewed 63 times
-2
-
What do you mean? The size of an array is not in the declaration in java. – tkausl Dec 22 '18 at 08:28
-
*"objects has a dynamic capacity in java"* Huh? – Andreas Dec 22 '18 at 08:29
-
for example : int [ ][ ] arrays = new int [3 ][ ]; or int [] arrays = new int [ 3]; – ehsan nikkhah Dec 22 '18 at 08:30
-
Java arrays are not dynamically sized. They are fixed-size, once created. Array *declarations* don't specify a size. The size is specified when the array is *created*. --- `int [ ][ ] arrays` declares the array. `new int [3 ][ ]` creates/initializes the array. – Andreas Dec 22 '18 at 08:30
-
Hey Guys : given that I want create a arrays with dynamic size.in this case I can't declare an array in the below code : int [ ] arrays = new int [ ] , and I must declare it as below : int [ ] arrays = new int [ one constant value ]; – ehsan nikkhah Dec 22 '18 at 08:39
-
@ehsannikkhah You can't use an array without a fixed size. But you can use an ArrayList instead of a array for this like I have explained in my answer. List
list = new ArrayList(); here you don't have to specify the size – Sandeepa Dec 22 '18 at 08:43 -
thanks to all , but I have still ambiguity.array in java is an object , and objects created in heap for allocate dynamically memory,what's reason that arrays in java must have a fixed size ??? – ehsan nikkhah Dec 22 '18 at 08:58
-
Objects have a fixed size, determined at creation time. https://stackoverflow.com/questions/53203194/how-can-the-jvm-allocate-memory-for-objects-despite-the-possibility-that-they-mi – Raedwald Dec 22 '18 at 09:35
2 Answers
2
Your question is bit confusing. But the size of the array is not defined in the array declaration. It's defined when an array is created. When you assigned a created array to your declared array variable.
You have to do this because Java arrays are of fixed size and not dynamically resized. You can use ArrayList
instead of array if you don't want the size to be fixed.

Tom Hawtin - tackline
- 145,806
- 30
- 211
- 305

Sandeepa
- 3,457
- 5
- 25
- 41
-
You can declare an array reference with a null value - no need of instantiation there... – Mustehssun Iqbal Dec 22 '18 at 08:35
-
Just adding to your answer... trying to explain difference between declaration and instantiation to @ehsan... – Mustehssun Iqbal Dec 22 '18 at 08:40
-
1
It has nothing to do with java. Allocating memory for arrays is almost the same thing in java as using malloc in C.

Mustehssun Iqbal
- 576
- 3
- 19
-
This might be of help: https://stackoverflow.com/questions/2099695/is-a-java-array-of-primitives-stored-in-stack-or-heap – Mustehssun Iqbal Dec 22 '18 at 08:33