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

Dylan Carter
Dylan Carter
4,780 Points

why wont this work??

import com.example.BlogPost;

public class TypeCastChecker {
  /***************
  I have provided 2 hints for this challenge.
  Change `false` to `true` in one line below, then click the "Check work" button to see the hint.
  NOTE: You must set all the hints to false to complete the exercise.
  ****************/
  public static boolean HINT_1_ENABLED = false;
  public static boolean HINT_2_ENABLED = false;



  public static String getTitleFromObject(Object obj) {
   if (obj instanceof String) {
  return (String) obj;
}
  }
}

I get one error saying that return value is expected but I have clearly put one and checked this against other answered questions of the topic and I cant find what I am doing wrong.

can someone please give me some insight on why this is doing this?

1 Answer

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Dylan,

you are almost there :)

This block proofs whether obj is a String and returns obj casted as a String. Thats correct.

  public static String getTitleFromObject(Object obj) {
   if (obj instanceof String) {
  return (String) obj;
}

But what if obj is a BlogPost. You can use an else statement and after casting obj to BlogPost you can access the getTitle method of the BlogPost and return it. Title is a String so you will get a proper return type ....

You can do it this way:

 if (obj instanceof String) {
      String result = (String) obj;
        return result;
    } else {
      BlogPost bp = (BlogPost) obj;
        return bp.getTitle();
    }

or this way:

 if(obj instanceof String){
      return (String) obj;
    } else {
      return ((BlogPost) obj).getTitle();
    }

Grigorij

Christian Lawrence
Christian Lawrence
3,941 Points

I was also stuck of this and found it hard to decode the origional question. Would I be right in saying the above code is checking:

  • if the object passed is a String just return whatever that string is,
  • otherwise it is a BlogPost, return the title (a string) of that BlogPost object

?