1
class ArrayApp{

    public static void main(final String[] args){

     long [] arr; 
     arr= new long[100];
     int i;
     arr[0]=112;
     arr[1]=111;
     for(i=0;i<arr;i++) {
     System.out.println(arr[i]);
     }

  } 
} 

I get this error,

ArrayApp.java:10: operator < cannot be applied to int,long[]
        for(i=0;i<arr;i++) {
                 ^

6 Answers 6

5

You need to use the size of the array, which would be arr.length.

for (int i = 0; i < arr.length; ++i)

As of Java 1.5, you can also use the for each loop if you just need access to the array data.

for ( long l : arr )
{
    System.out.println(l);
}
Sign up to request clarification or add additional context in comments.

Comments

2

arr is an object of long[] , you can't compare int with it.

Try arr.length

Alternatively You should go for

for(long item:arr){
System.out.println(item);
}

Comments

1

You want arr.length

2 Comments

Now if i want to show only the values which are filled and not show the rest of blocks which dont have any value.
Then have a check before printing the value, what's the problem?
1

The question has to be seen in the context of a previous question!

From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.

In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):

long[] arr; 
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2;  // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {  
  System.out.println(arr[i]);
}

Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:

List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
  System.out.println(value);

Comments

0
Long arr = new Long[100];
 arr[0]=112;
 arr[1]=111;
for(int i=0;i<arr.length;i++) {
  if (arr[i] != null ) {
    System.out.println(arr[i]);
  }
}

if you want to show only those which are filled.

Comments

0

You can solve your problem using one line of code: Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");

See http://java.dzone.com/articles/useful-abuse for more similar tricks.

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.