1

This is regarding java programming.Why Java developer has made length() as member function for String Object while for array reference variable they made it as final field?... If that is not really confusing then My next question is as in any function, references are local variable stored on Stack.Then how we are able to refer field on array reference.. Please correct me if I went somewhere wrong..

3 Answers3

0

The length of an array isn't even a field (it can't be because arrays aren't real objects). It's a "pseudo-property" like the class in Object.class. It's a syntactic element recognised by the compiler and translated into some primitive operation.

Tobias Brandt
  • 3,393
  • 18
  • 28
  • Which Object.class are you talking?..I mean i was unable to find any property you mentioned – Level29Access Aug 22 '13 at 14:14
  • I didn't find anything like property for an array or for any other class in API.http://docs.oracle.com/javase/6/docs/api/ – Level29Access Aug 22 '13 at 14:18
  • @Level29Access: That's exactly what I'm saying. There is no array class because an array is not a normal object. And that's why `length` is not a normal field (in what class would it be defined?). The compiler translates an expression like `a.length` into the JVM instruction `arraylength`, not a field access. – Tobias Brandt Aug 22 '13 at 14:36
  • Similarly, `Object.class` is translated into a reference to an instance of type `java.lang.Class` describing the class `Object`. – Tobias Brandt Aug 22 '13 at 14:38
-1

If you see the source code of string,That scenario comes when you pass a chararray to the String constructor.

  public More ...String(char value[]) {
193         int size = value.length;
194         this.offset = 0;
195         this.count = size;
196         this.value = Arrays.copyOf(value, size);
197     }

And making count as a final Prevented to intialize the count outside of the constructor.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
-2

"Why" questions are always the hardest to answer. Historical reasons mostly arising from special treatment of arrays. I think properties should be restricted to simple get and set, only if there are no side effects, otherwise use functions.

Yimin Rong
  • 1,890
  • 4
  • 31
  • 48
  • See below code: int []a; a=new int[4]; a.length=8;//Compile Time Error The Final field array.length cannot be assigned. – Level29Access Aug 22 '13 at 13:49
  • @Level29Access You "set" the size by initializing it whith "4". Of course you cannot change a final var. – Fildor Aug 22 '13 at 13:51
  • @Fildor That what exactly I mean to say it is final..So,Why developer didn't made it method like in String class. – Level29Access Aug 22 '13 at 13:53