Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Getting There Type Casting

Ciaran McNally
Ciaran McNally
7,052 Points

Why do we have to typecast obj?

Can someone please explain this to me,

So for the first part of the typecasting challenge we are using instanceof to check if obj is a String?

why then do we have to typecast obj to String when we return it?

 if(obj instanceof String) {
    return (String)obj;
    }

Am I missing something stupid? Are we down casting or up casting? I'm confused.

Thanks

1 Answer

Benjamin Barslev Nielsen
Benjamin Barslev Nielsen
18,958 Points

We are downcasting, since obj is of type Object and we are casting it to a String.

The typecast is necessary, since we need to tell the compiler that obj is of type String. Using the instanceof check ensures us as programmers that obj is in fact a String inside that if-statement, but the compiler still only knows that obj is an Object. Therefore we need to explicitly tell the compiler to treat obj as a String, which we do using the typecast.

Hope this helps