Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,811 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)