Java Java Data Structures Getting There Type Casting

Why can't I create the 'result' variable in the same line as the typecast?

Why does this following block not work? (Specifically the line: String result = (String) obj;)

if(obj instanceof String) {
    String result = (String) obj;            
}
else if(obj instanceof BlogPost) {
    BlogPost blog = (BlogPost) obj;
    result = blog.getTitle();
}

It doesn't let me declare 'String result' and cast it in the same line. I have to declare the string variable first and then typecast like this:

String result = "";

if(obj instanceof String) {
    result = (String) obj;            
}
else if(obj instanceof BlogPost) {
    BlogPost blog = (BlogPost) obj;
    result = blog.getTitle();
}

I want to know why the first method does not work. Afterall, it works for:

BlogPost blog = (BlogPost) obj; 

so why would it not be the same for:

String result = (String) obj;

1 Answer

Gyorgy Andorka
Gyorgy Andorka
13,809 Points

The problem is not with typecasting, but with scope: technically you can declare a variable inside the if-block and initialize it on the same line, but it will only be visible inside the block - the else if branch will not see it and cannot use it. That's why you should first declare result above.

In case of blog, you can declare and initialize it inside the block, since you only intend to use it on the next line, still inside the else if block, in order to get the return value from getTitle() and assign it to result - which is the variable we'd like to return in the end (and, again, must be declared outside therefore)