• Post Reply Bookmark Topic Watch Topic
  • New Topic

.length and .length() what  RSS feed

 
Marvin Porte
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! this is my second question, I'm a beginner java programmer. I just want to know the difference between this two and why i can't use this interchangeably.

It happens when I'm trying to code nums.length (where nums is an array). I thought it would be the same with str.length() (where str is a string). I just confused.
 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the case of arrays, 'length' is a class variable that holds the number of indices in the array instance. In the case of Strings, length() is a method (not a variable) that returns the length of a String.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some of us here think it might have been poor communication which resulted in Strings having a length() method and arrays a length field and Lists a size() method.
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joel Christophel wrote:In the case of arrays, 'length' is a class variable that holds the number of indices in the array instance.

length is not a class variable it's an instance variable.

Every array in Java is an object which has a property called length which, as Joel has correctly stated, holds the number of indices in that array.

Campbell Ritchie wrote:Some of us here think it might have been poor communication which resulted in Strings having a length() method and arrays a length field and Lists a size() method.

I'm in that camp too. Its particularly confusing for beginners.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!