3

I have the following:

int count = args.length;

Strange as it might seem I want to find out the array length without using the length field. Is there any other way?

Here's what I already (without success) tried:

int count=0; while (args [count] !=null) count ++;
int count=0; while (!(args[count].equals(""))) count ++;}
2
  • You could try accessing successive character positions until you get an out of bounds exception. Not that I would recommend doing that...
    – Eric J.
    Commented Jun 28, 2012 at 1:12
  • Well, you get an IndexOutOfBoundsException if you access an element beyond the end of the array, so you could always iterate inside a try/catch block, and note the index that first threw the exception.
    – dlev
    Commented Jun 28, 2012 at 1:13

6 Answers 6

5

I don't think that there is any need to do this. However, the easiest way to do this ,is to use the enhanced for loop

 int count=0;
 for(int i:array)
 {
   count++;
 }

 System.out.println(count);
0
3

I'm not sure why you would want to do anything else, but this is just something I came up with to see what would work. This works for me:

    int count = 0;
    int[] someArray = new int[5];  
    int temp;
    try
    {
        while(true)
        {
            temp = someArray[count];
            count++;
        }
    }
    catch(Exception ex)
    {
           System.out.println(count); 
    }
2
  • 4
    We do try not to promote worst practices (such as using exceptions for control flow, particularly in lieu of better alternatives), because the strange thing is people tend to find and use them. Commented Jun 28, 2012 at 1:19
  • Ah ok, yeah I wouldn't recommend anyone actually using this approach. The best way would always be to use .length, to the best of my understanding. Commented Jun 28, 2012 at 1:35
0

You cannot use [] to access an array if the index is out of bound.

You can use for-each loop

for (String s: args){
    count++;
}
0
public class ArrayLength {
    static int number[] = { 1, 5, 8, 5, 6, 2, 4, 5, 1, 8, 9, 6, 4, 7, 4, 7, 5, 1, 3, 55, 74, 47, 98, 282, 584, 258, 548,
            56 };

    public static void main(String[] args) {
        calculatingLength();
    System.out.println(number.length);
    }

    public static void calculatingLength() {
        int i = 0;
        for (int num : number) {

            i++;

        }
        System.out.println("Total Size Of Array :" + i);

    }


}
0
    int[] intArray = { 2, 4, 6, 8, 7, 5, 3 };
    int count = 0;
    // System.out.println("No of Elements in an Array using Length:
    // "+intArray.length);

    System.out.println("Elements in an Array: ");
    for (int i : intArray) {
        System.out.print(i + " ");
        count++;
    }

    System.out.println("\nCount: " + count);
-4

How about Arrays.asList(yourArray).size();?