Transcript for:
Essentials of Casting in Programming

hi in this video we're going to talk about casting so integers and doubles can be a little bit confusing sometimes what if you want to your int to be a double or your double to be an int introducing casting casting is turning something of one type into another type so for example let's say we have the double 5.3 and we want to turn it into an int to cast it as an int we write open parenthesis int close parentheses before the number and it'll turn it into the int 5. so you add the type you want in between parentheses to cast to that type so to cast an into a double let's say you have x as an integer 5 and you want it to be a double you put double in parentheses before x and so y is now a double with the value 5.0 if you want to cast a double to an end so you have the double x as 10.3 and you want y to be an int you put int in parentheses and now why is the value 10. interestingly you can actually cast from an int to a double without using double in parentheses this is referred to as implicit casting implicit casting is when java automatically casts the value correctly without the programmer needing to do so java will cast an int to a double but will not be able to cast a double to an int implicitly so let's go back to division remember so here we have a total equal to 100 into num people equal to 40 and now if we say double average equals total divided by num people this would have the value 2 which is not what we would want and it has that because of integer division so to get around this what we would do is try and cast one of them to a double then we'll get the correct result so you can see we cast total to a double first before dividing it remember mixed division where one is a double and one is an int will return a double so this would have the value 2.5 so let's go into our editor and look more at this problem okay so here we have that code in total is equal to 100 in num people is equal to 40 double average equals total divided by num people so let's print this out and see what happens [Music] okay so we can see the average is 2.0 which isn't right but we're getting that answer because of integer division what we want to do is we want to cast total as a double and if total is treated as a double we should get the correct result there you go we can see the average is now 2.5 which is what we're expecting additionally you can note that we could also cast num people as a double and we'd still get the correct result so that's how you use casting