public class NewClass {
    public static void main(String[] args){
    int[] a=null;
    int p=0;
    int i=0;
    while(p<11){
    a[i]=p;
    p++;
    i++;
    }
    }
}

what is wrong here.....here the array can not store data.

Edited 4 Years Ago by Onlineshade

In java u have to dynamically alocate resources for array...
for Line 3 you need
a = new int[size of array];

@Onlineshade ,
It wil lshow null pointer exception at line 7,
because of line 3,

 // declares an array of integers
    int[] anArray;

    // allocates memory for 10 integers
    anArray = new int[10];
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * 
 */
public class NewClass {
    public static void main(String[] args){
    int[] a;
    a=new int[10];
    int p=0;
    int i=0;
    while(p<11){
    a[i]=p;
    p++;
    i++;
    }
    }
}



Still some problems....oh!
**Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
   at NewClass.main(NewClass.java:17)
  Java Result: 1
 BUILD SUCCESSFUL (total time: 0 seconds)**

Edited 4 Years Ago by Onlineshade

The ArrayIndexOutOfBounds is happening due to the while loop.
while (p<11)
this executes 0-10.
However our range is from 0-9. (Because we have an array of 10 integers)

change while (p<10) and I guess your code should work fine :)

You have to declare the size of an array before you can put and retrieve data from it.. Otherwise it will create an error..

while(p<11){

a better approach would be to change the above to:

while (p < a.length)

since you don't always know the length up front. this way, you won't reach an arrayIndexOutOfBoundsException, whether you keep the same number of elements or decide to change that number.

This article has been dead for over six months. Start a new discussion instead.