user1464139
user1464139

Reputation:

Can I find out the length of an array without using .length in Java

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 ++;}

Upvotes: 3

Views: 22950

Answers (6)

Nikhil Chaudhari
Nikhil Chaudhari

Reputation: 1

    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);

Upvotes: 0

Rohit Tripathi
Rohit Tripathi

Reputation: 11

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);

    }


}

Upvotes: 0

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

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);

Upvotes: 5

Greg Wang
Greg Wang

Reputation: 1367

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++;
}

Upvotes: 0

Jeshurun
Jeshurun

Reputation: 23186

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

Upvotes: -4

Dan Teesdale
Dan Teesdale

Reputation: 1863

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); 
    }

Upvotes: 3

Related Questions