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
Ricardo Sala
16,212 PointsCASTING - What exactly does it do? What is the aim?
Good evening coders!
I am just a begginer and I like to understand the logic behind the things that I learn...
And honestly, I can't see what I am doing here!
In the case of the tweet for instance...it says something like:
"If it is a string, then cast it to string" EING? If it IS an instance of string, why should I need to cast it to string? Isn't it already a String??
Or it is not a String but it has the "shape" of a String and casting it to a String we are saying Java that we want to be able to use the String method because that's, in fact, a string?
Please, some good teacher here explain what's the logic behind casting...
I really think is a fundamental stone in our learning and is quite confusily explained!
Thank you!
1 Answer
Mohammed AlShaiban
6,455 PointsWe use casting when going from a general type to a more specific one. For example, you can store an Integer as a Number since Integers are numbers.
We can also use casting when we only want to output an integer, but we have a double. Let's say we have a double
double d = 9.99;
However, we only want to print it as integer, we can cast double to integer
System.out.println(d); //Will output 9.99
System.out.println((int) (d)); //Will output 9
It is important to note that casting will only work if the object is an instanceof the class we are casting to. If it is not, we will get ClassCastException