I've written the code (below) and the class courseCombinations works fine when created as a single entity, however as soon as it is made into an array I get an error: Exception in thread "main" java.lang.NullPointerException at genome.test(genome.java:9) at GATTer.main(GATTer.java:9)
publicint numberOf;
publicvoid courseCombinations(){
numberOf = 0;
}// End of courseCombinations
publicvoid printOut(){
for(int i = 0; i < 15; i++)
System.out.println("combinationsAre[" + i + "] = " + combinationsAre[i]);
}// End of printOut
} //End of class
public courseCombinations search[] = new courseCombinations[10];
then an array is created with 10 elements. The name of the array is search and it may contain 10 references of courseCombinations object. However, the above statement just creates the array named "search" and not 10 objects of courseCombinations class. All 10 elements of array have null reference after above statement is executed.
When you are using this statement: System.out.println("numberOf [0]: " + search[0].numberOf);
then all elements in search array are still null. YOU need a for loop to instantiate and store 10 ( or may be fewer depending on your needs). Since all elements are null serach[0] is null (it is first element) and you are getting null pointer execption. To correct this problem you need to add some code in test() constructor as:
publicvoid test() {
int total = 10 ;
for ( int i = 0; i < total; i++ ) {
// Populate search array with 10 objects
this.search[i] = new courseCombinations() ;
}
// other code goes here
}
Now you won't get null pointer exception.
Remember: 1. All array elements are initialized when you create the array. 2. Even local array is initialized. 3. For array of primitive type all elements have default value for that primitive type for example boolean false, numeric 0 etc. 4. All reference type array elements are initialized to null. 5. If you have a reference type array (in your case you do) then you must all created each element of array and assign the real reference.