2

I'm new to JAVA and I have a very simple question when I'm writing some codes. When should i use length and when should i use length()?

What's the difference between length and size?

Thank you!

SeaBiscuit
  • 37
  • 5
  • 3
    It varies by type. Arrays have a length field, collections have a size() and String a length(). – Elliott Frisch Dec 28 '14 at 05:01
  • 1
    length is used for arrays and size() is used for collections – svkvvenky Dec 28 '14 at 05:04
  • What @ElliottFrisch said. Also, `StringBuffer` and `StringBuilder` have `length()`. So does `File`. So do many other less-used classes--see http://docs.oracle.com/javase/8/docs/api/index-files/index-12.html and scroll down to see what JRE-defined classes have `length()`. – ajb Dec 28 '14 at 05:06
  • For the god sake first search Google. Really it takes less time than posting this simple question here. Check [this](http://stackoverflow.com/questions/9297899/arrays-length-property) – Hana Bzh Dec 28 '14 at 05:13

1 Answers1

0

length --- arrays (int[], double[], String[]) ---- to know the length of the arrays.

length() --- String related Object (String, StringBuilder etc)to know the length of the String

size() --- Collection Object (ArrayList, Set etc)to know the size of the Collection

as length is not a method its works on arrays not on objects.

size() is a method which work on collection frameworks as i said up there .

now String is not a direct array and also not a Collection that's why we also need a different one which is length().

Saif
  • 6,804
  • 8
  • 40
  • 61
  • Oh i got it. But what's the difference between length and size? – SeaBiscuit Dec 28 '14 at 05:05
  • 1
    @SeaBiscuit I think collections have `size()` because they're not necessarily in a sequence. `Set` and `Map` collections don't have any order to them, and it doesn't seem right to talk about the "length" of one of those. The consequence is that `List`, which is a subclass of `Collection`, has `size()` instead of `length()`, which takes some getting used to. Maybe they should have defined `length()` as a synonym for `size()` for `List`... oh, well. – ajb Dec 28 '14 at 05:15
  • that is an nice explanation. I would be glad if you edit the answer to add this portion @ajb – Saif Dec 28 '14 at 05:18