That is because there is nothing wrong with the code, AS IS. Do like helloworld922 said, and try to USE the object3, and that is a different story. Code below.
This has everything to do with this thread, as it is a headbutt with a reply.
public class ObjectInitialization {
Object object1;
static Object object2;
public static void main(String[] args) {
Object object3;
if(object1 == null){}//compile error:
//Cannot make a static reference to the non-static field object1
if(object2 == null){}//ok, but see notes below..
if(object3 == null){}//compile error:
//The local variable object3 may not have been initialized
}
}
Simply declaring a variable is like walking into a store and grabbing an empty shopping cart. You now have a place to store something.
When you use the new keyword it is like putting something in the cart.
Try walking up to the cashier with an empty basket and ask what you owe. If you want to access the price of an item (or any other field) you have to put an object in the box first.
While you may be able to avoid initialization, as in object2, you shouldn't. There are times you could forget to init a variable, (or just skip it), and just as luck would have it, what ever garbage in that memory location turns out to be suitable your code's needs. Now you have a bug you did not find, and will see eventually. (usually after your assignment is turned in)
If you initialize all of your variables you remove the possibility of ever having the error, and you always know what is inside. If you want to check vs null, assign a null value on init. If you need an object later, assign it later. There is no rule that says you can not initialize all of your variables, so why not make sure to overwrite any memory garbage with a definition as you declare each variable. ....keep in mind primitive types (including String) have their own defaults...