I was learning about arrays in Java and the line .length
was frequently used to find the size or length of the array. But when I reached the topic of "Strings", unexpectedly .length
became .length()
, the most amusing thing is that they were performing the same task i.e to return the length.
Now, most people would just skip through by cramming that one is used for arrays and one for strings without delving too deeply into the topic but not your boy.
After contacting my research department I came to know that:-
The
.length
is an instance variable of an array in Java whereas length() is a method of String class.
Okay, but what does this mean?
Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. These variables are created when an object of the class is created and destroyed when the object is destroyed.
In layman's terms, when you create an array (which is an object) the instance variable .length
becomes available for you to use.
Whereas, .length()
is a static method of String class.
Now, the question arises, why use different ways to perform the same task? The string class uses this method because the length of a string can be modified using the various operations on an object. The String class internally uses a char[] array that it does not expose to the outside world.
On the other hand, Once arrays are initialized, their length cannot be changed, so the .length
variable can directly be used to get the length of an array.
I hope this was helpful. (ɔ◔‿◔)ɔ ♥
Let's connect on Twitter.