When creating an object(or anything) in java, what is the difference between doing, for example,
Dog d = new Dog();
instead of doing
Dog d;
and then later, finishing it off(sometimes inside and at the beginning of a method) with
d = new Dog();
Wouldn’t the first one be more simple and easier? Why do people do it the second way?
Think of the following scenario. Assume the constructor of
Dogcan throw an exception:This won’t compile because
dis not visible outside thetryblock. What you need to do is this:And there are many other situations like this. For example, you might have an if-else block where
dis initialized differently based on some condition: