17

below is my code which is throwing error:

Cannot invoke size() on the array type int[]

Code:

public class Example{
int[] array={1,99,10000,84849,111,212,314,21,442,455,244,554,22,22,211};    
public void Printrange(){

for (int i=0;i<array.size();i++){
    if(array[i]>100 && array[i]<500)
{
System.out.println("numbers with in range ":+array[i]); 
}


}

Even i tried with array.length() it also throwing the same error. When i used the same with string_name.length() is working fine.

Why it is not working for an integer array?

2

7 Answers 7

32

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();
Sign up to request clarification or add additional context in comments.

Comments

2

I think you are confused between size() and length.

(1) The reason why size has a parentheses is because list's class is List and it is a class type. So List class can have method size().

(2) Array's type is int[], and it is a primitive type. So we can only use length

Comments

1

Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length

public class Example {

    int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};

    public void Printrange() {

        for (int i = 0; i < array.length; i++) {
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range" + i);
            }
        }
    }
}

1 Comment

array.length is what you want!
0

There is no method call size() with array. you can use array.length

Comments

0

Array's has

array.length

whereas List has

list.size()

Replace array.size() to array.length

Comments

0
public class Test {

    int[] array = { 1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554,
            22, 22, 211 };

    public void Printrange() {

        for (int i = 0; i < array.length; i++) { // <-- use array.length 
            if (array[i] > 100 && array[i] < 500) {
                System.out.println("numbers with in range :" + array[i]);
            }
        }
    }
}

Comments

0

we can find length of array by using array_name.length attribute

int [] i = i.length;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.