Yishu Fang
Yishu Fang

Reputation: 9958

Why int a[10] is not allowed in java?

I am beginning to learn java, I find that in the declaration of an array we cannot specify the size of it like this (which is used in C):

int a[10];

But we have to do like this:

int[] a=new int[10];
int a[]=new int[10];

Why java seems to be complex in here instead of allowing array declaration like the C style?

Upvotes: 1

Views: 1148

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200158

This is a part of a much larger picture: there are no stack-allocated structures in Java. That is why the type system can be partitioned into primitive types and reference types. Instances of the latter are dynamically allocated and accessed via references. This is a deep invariant of Java design.

The reason for this can be tracked down to the key driving goal of Java's design: to be a simple language with as few gotchas as possible, while still offering adequate expressiveness.

You may ask what is so complicated about a stack-allocated array: the trouble starts when you try to pass it into another function. Passing by value is out of the question and passing by reference means the reference to a stack-allocated object escapes the method's scope, so it may be dereferenced after deallocation.

Upvotes: 0

Anshul Gupta
Anshul Gupta

Reputation: 68

In java arrays are objects. Java wrap these bare-bone arrays within an object hence All methods of an Object can be invoked on an array.

**int a[]** = new int[5];

5 inside the square bracket says that you are going to store five values and is the size of the array ‘n’.

  1. Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  2. Instantiation: The new keyword is a Java operator that creates the object. and since in java arrays are objects, it is necessary.

  3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

NB.

In java,Memory is constantly being allocated dynamically(objects are allocated memory dynamically by new operator) and then "forgotten" (the language actually forces you to forget about them). That is, the coder leaves it to the garbage collection engine to clean up his memory allocation mess. In C, concept of static memory allocation allow declaration of

int a[10];

References : Java Arrays

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881403

Because Java is not C. It shares some common idioms with C (quite a few actually) but the Java language developers were not totally beholden to the C language in their efforts.

The arrays themselves are objects stored on the heap, hence the need to do a new to create them. The reference a[] to the array may well be stored on the stack but that's not the array itself.

Upvotes: 14

Related Questions