0

How could we statically declare array? Can't it be by int a[5];?

package oops;

public class exception { 
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}
demongolem
  • 9,148
  • 36
  • 86
  • 104

3 Answers3

4

Consider the following scenarios

// Create new array with the following two values
int a[] = {1,9};
Assert.assertTrue( 2 == a.length );
Assert.assertTrue( 1 == a[0] );
Assert.assertTrue( 9 == a[1] );

// Create a new, uninitialized array
int[] a;
Assert.assertTrue( null == a );
Assert.assertTrue( 0 == a.length ); // NullPointerException

int a[9]; // this will not compile, should be
int a[] = new int[9];
Assert.assertTrue( 9 == a.length );
Assert.assertTrue( null == a[0] );

// Provided 'a' has not been previously defined
int a[];
a[0] = 10; // NullPointerExcpetion

// Provided 'a' has been defined as having 0 indicies
int a[] = new int[0];
a[0] = 10; // IndexOutOfBoundsException

// Provided 'a' has been defined as an empty array
int a[] = new int[1];
a[0] = 10; // Reassign index 0, to value 10.
Matt Clark
  • 26,491
  • 18
  • 65
  • 118
2

int a[] = {1,9} is an array of two elements 1 and 9 int[] a is declaring an integer array called a. Not initialized. int a[9] is an array containing nine elements. Not initialized int[0]=10 places the value 10 in position 0 on the array

Robert Juneau
  • 602
  • 6
  • 15
MaxPower
  • 851
  • 7
  • 25
0

int arr1[] = new int[10]; - > an empty array of size 10 (memory allocated for it)

int a[] ={1,9}; -> [1, 9] (creates an array with the values of 1 and 9)

int[] a ; -> array that has been declared but not initialized

int a[9]; -> doesn't work

See Arrays

Blubberguy22
  • 1,315
  • 17
  • 27