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


Matthew Francis
Matthew Francis
6,967 Points

What is the purpose of "Casting" and whens should you use it?

After watching an introductory video on it I understand how it works and all but I'm unsure when and why you should use it, an explanation would be great!

1 Answer

Wout Ceulemans
Wout Ceulemans
17,603 Points

Lets say you have an instance of type Object. You are certain that this object is a String, but you cannot use any String related methods on your instance because it is still of type Object. What you then can do is cast it to a String, and thus be able to use String related methods.

Object o = "Hello";
String s = (String) o;

You can cast an object to another type to obtain methods and fields that where otherwise not accessable. Be always sure that the object can be casted to the target type. You can always cast an object to one of his parent class (eg: String to Object). Casting a parent class to a childclass is also possible, but this could go wrong and throw an ClassCastException.

Casting to parent class:

String s = "Hello";
Object o = (Object) s;

Casting to child class:

Integer i = new Integer(5);
Number n = (Number) i;
Integer i2 = (Integer) n;

I'm not a Java professional, but I hope this gives you a good explanation.