How to get the size of an array in Java?

To get the size of an array in Java you can simply use the length property. So for an array “xyzArray”, you can just do “xyzArray.length” and that will get you the size (or length) of the array.

Here is some simple example code as well:

Code example – find the size of an array in Java:

int[] someArray = new int[3];

/*this will give you the size of the array,
  which is 3 in this case:
*/

int arraySize = someArray.length;

Length is a property not a method

You should also remember that “length” is a property for arrays and not a method – which is why we don’t use parentheses at the end to find an array length. So, we do not do this “someArray.length()”.

String length() versus array length

To get the length of a String, we can simply call the length() method of the String class. So, for some string “aString”, we could just call aString.length() to get the length.

Let’s contrast that with how we get the length of an array with some example code:

String length() versus array length example

String aString = "hello";
int stringLength = aString.length();

int[] someArray = new int[3];

//note the slight syntax difference to get the length:
int arraySize = someArray.length;

To summarize something that could potentially confuse you in an interview situation – use the length property for arrays, but the length method for Strings. A quick example – for arrays: someArray.length, but for Strings: aString.length().





Follow Varoon Sahgal, author, on Google Plus