Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: When declaring objects or ints

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?

like image 791
GlassZee Avatar asked Jul 11 '26 10:07

GlassZee


1 Answers

Think of the following scenario. Assume the constructor of Dog can throw an exception:

try {
    Dog d = new Dog();    
} catch(Exception ex) {
    // treat exception
}

d.bark();

This won't compile because d is not visible outside the try block. What you need to do is this:

Dog d = null;
try {
    d = new Dog();    
} catch(Exception ex) {
    // treat exception
}
if(d != null) d.bark();

And there are many other situations like this. For example, you might have an if-else block where d is initialized differently based on some condition:

Dog d = null;
if(/* condition */)
    d = new Dog("Lassie");   
} else {
    d = new Dog("Sam");
}
d.bark();
like image 74
Tudor Avatar answered Jul 13 '26 23:07

Tudor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!