I'm pretty new at Java and I'm having a tough time figuring out how to fix this null pointer exception that has been troubling me.
I know where the problem occurs and I know what a null pointer exception is, but I have no idea how I'm going to make my program work.
Here's the code snippet where the problem is occuring:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Account[] atm = new Account[10];
for (int i = 0; i < 10; i++){
atm[i].setId(i);
atm[i].setBalance(100.00);
}
Like I said, I know that it happens because the objects in atm[] are null, but I'm not sure how to fix the problem.
I'm sure it's some silly mistake because those are the kinds of mistakes I make on a regular basis, but any help that you guys can give would make my day.
Thanks!
Array elements are initialized to 0 if they are a numeric type ( int or double ), false if they are of type boolean , or null if they are an object type like String .
An array value can be non-empty, empty (cardinality zero), or null. The individual elements in the array can be null or not null.
To set all values in an object to null , pass the object to the Object. keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null . After the last iteration, the object will contain only null values.
You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class.
Your entire array is null ! remember , arrays are never automatically initialized in java, unless they are arrays of ints,floats,doubles, or booleans.
Scanner input = new Scanner//System.in.Scanner;
Account[] atm = new Account[10];
for (int i = 0; i < 10; i++){
**atm[i] = new Account();**
atm[i].setId(i);
atm[i].setBalance(100.00);
}
When you're declaring arrays that hold objects, read it as, "I'm creating an array that will hold 'x' objects." (correct), and then proceed to instantiate those objects
...as opposed to...
"I'm creating an array with 'x' objects in it." (incorrect) since there aren't any objects in there yet because they haven't been created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With