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

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.


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