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).
Does that code actually compile? I am surprised you get a null exception, because it should produce a compiler error that the array has never been initialised.
You do not need to know what is going on in terms of memory or pointers. Also remove the no‑arguments constructor from the Employee class, because that is a potential source of errors.
posted 5 years ago
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:
yes but a quiz! And grant a cow for someone who answers all questions on it! ...nah, I am digressing. Its ok. Good day guys.
posted 5 years ago
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.
I'm a lumberjack and I'm okay, I sleep all night and work all day. Lumberjack ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop