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

Android

Types of casting

Hi,

I´m a little confuse about when I use, parse or, toString(), or this example: mStartButton = (Button) findViewbyId(R.id.startButton);

What the difference between then?

When do I use:Ex -parseString -toString()

  • or (String) findViewxxxxxxxx

This is all diferent types of casting?

1 Answer

Ben Deitch
STAFF
Ben Deitch
Treehouse Teacher

Object.toString() is a method that returns a string that "textually represents" the object in question. And since this method is on the Object class, every class that extends the Object class (aka every class, since all classes either directly or indirectly extend the Object class), will have a 'toString()' method.

Integer.parseInt(String arg) (or Float.parseFloat, or Double.parseDouble...) takes in a String (formatted as a number) and converts it to an int.

(Button) is a cast. findViewById(...) returns an object of type View, but we can't put an object of type View into our mStartButton variable; it's expecting an object of type Button. So since we know that R.id.startButton represents a Button, we can just add the cast, (Button), to cast it to a Button object.