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

edumorlom
edumorlom
4,073 Points

Why doesn't my code work for TASK 1?

If the Object that is passed in instanceof String, it'll convert it, otherwise it will just return the object. Why isn't this code working?

public static String getTitleFromObject(Object obj) {
    Object result = new Object();
    // Fix this result variable to be the correct string.
    if (obj instanceof String)
    {
      result = (String) obj;
    }
    else
    {
      result = obj;
    }
    return result;
  }

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Eduardo - The method is supposed to return a String but if obj is not an instance of String you're returning and instance of Object. So leave result's definition as was given:

String result = "";
if (obj instanceof String) {
    result =  (String) obj;
}
return result;