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 - Retired Getting There Type Casting

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Type casting ... confused

Hey everybody. hey Craig .... i dont understand the explanation to this question ...

https://teamtreehouse.com/forum/confused-by-type-casting

The explanation code is this:

String example = "This is an example";

public int justSomeExampleToShowTypeCastingOff(Object obj) {
   if (obj instanceof String) {
        String str = (String) obj;
        return str.length();
   }
   // Otherwise, I don't know how to figure out the length
   return 0;
}

// Call the method even though it takes an Object, I will pass in a String
justSomeExampleToShowTypeCastingOff(example);

We want to use methods from a String class and thats why we cast Object to String, right?

But for me it is down-casting ! So for my understanding it must look like this

Object obj = new String();

In the explanation we are up-casting the String to Object ?????? Why?

String str = (String) obj;

1 Answer

Chris Adamson
Chris Adamson
132,143 Points

The reason you have to upcast to String is because obj is pointing to the parent class of String, which doesn't have the methods you want to calculate the length the String length. If you declared it like:

String obj = new String();

you wouldn't need to cast because it would be of the type you need.