Question about a Java array's length property

I know that Java's array's length property is defined as public final. My question is, how does the array set a value to that 'length' property if it's final?

For example, if I do:

int arr = new arr[5];

At this point, how does array assign the number 5 to its length property internally if the 'length' property is final?
elepilAsked:
Who is Participating?
 
Phil PhillipsConnect With a Mentor Director of DevOps & Quality AssuranceCommented:
No, it's just like any final variable.  Final variables are allowed to be set one time.  When you do:

int[] arr = new int[5];

It is essentially creating a new array object, and setting its length value for the first time.  You can do the same thing with your own objects:

public class Test {
   private final int someFinalValue;
   
   public Test(int somefinalValue) {
      // First time the final int is being set - can no longer set it after this
      this.someFinalValue = someFinalValue;
   }
}

Open in new window

0
 
Phil PhillipsDirector of DevOps & Quality AssuranceCommented:
That is allowed in that case because that's the first (and only) time 'length' is being set ('final' allows for the value to be set exactly once).
0
 
elepilAuthor Commented:
Thank you for your response, Phil.

Are you saying Java made a "special consideration" that despite being a public final variable, Java allowed array's 'length' to be assigned a value, and that I cannot replicate such a behavior in my own classes?
0
 
elepilAuthor Commented:
Ah, thank you for that code sample, that made it clear.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.