Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialThomas Williams
9,447 PointsSystem.out.printf("There are %d treets. %n", treets.length); WHY DOES .length NOT REQUIRE '()'
I thought methods required braces, how come (.....code...treets.length) works?
1 Answer
hbdc
13,725 PointsI believe it's down to the way arrays actually are. Since the length of the array is immutable it's stored in a final variable (constant). The length of the array will not change regardless of how many elements there are in the array as it's immutable.
On strings you use the .length() method to calculate the number of elements in the array of strings.
Not 100% sure on this one, but it kind of makes sense.
Thomas Williams
9,447 PointsThomas Williams
9,447 PointsThanks for the swift reply Yani, it sent me in the right direction for researching the answer. From the article below I believe that in arrays, 'length' is actually a field rather than a method which is possible due to the reasons you listed above, the length is set on creation.
"Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The public final field length, which contains the number of components of the array. length may be positive or zero."