The problem, as you said, is that the newEmployee reference is declared, but never initialized, meaning that at line 5 you are trying to store a reference to a new Employee instance at index 0 of an array that doesn't exist.
Initializing the array directly after you declare the reference at line 4 will fix that. This tutorial might help you.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Are you from a C++ background? If so then Java works differently to C++. As Jelle has pointed out you always have to assign a value to references to objects otherwise the reference will be null (if it is a class or instance field), or will fail to compile (if its a local variable).
No, the code did not compile. However, when I declared the array as "Employee newEmployee = null", I got it compiled but it threw the run time error.
I have been coding in IBM i for 8+ years (COBOL and RPG ). Java is very new to me, please excuse if I ask way too basic questions. I believe in writing silly programs like these. This makes me understand the concepts and to be able to identify the issue if it were to occur again (though you guys might facepalm)
I have removed the no argument constructor, something isn't right yet:
If you look in the books, they tell you that a constructor is there to enable you to instantiate a class. But the truth is, the constructor is there to restrict instantiation. If you have one constructor with
String int as the parameter types, that tells users, “yes, you can instantiate this class but you must provide me with a String and an int.”
You can add more constraints to it, for example:-You can read about requireNonNull here. There are other ways to verify the contents of a String.
If you look in the Java® Language Specification (this is one of the few parts easy to understand), you find that you can use the access modifier on the constructor to restrict instantiation a different way.
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
Free, earth friendly heat - from the CodeRanch trailboss