You cannot - there is no difference between an element that has not been set and an element that has been set to 0. The actual length of the array is 5 and will always be 5. (Arrays cannot change length after creation.)
Of course, if you know you will never use 0, you can write:
int size = 0; for (int value : a) { if (value != 0) { size++; } }
... but if you are trying to use an array as a buffer with a live segment at the beginning (for example, an ArrayList ), you will have to maintain this size yourself.
source share