Shiva Krishna
Shiva Krishna

Reputation: 193

How to find integer array size in java

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?

Upvotes: 17

Views: 145669

Answers (7)

Suman Behara
Suman Behara

Reputation: 160

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

Upvotes: 1

munmunbb
munmunbb

Reputation: 417

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

Upvotes: 2

Varun
Varun

Reputation: 7

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

int [] i = i.length;

Upvotes: 0

Arun Kumar
Arun Kumar

Reputation: 2934

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

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26067

Array's has

array.length

whereas List has

list.size()

Replace array.size() to array.length

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

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

Upvotes: 0

user1907906
user1907906

Reputation:

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

Upvotes: 32

Related Questions