Java Lesson 13 | Typecasting
Hey, this is uh Maads 101. This is going to be my 12th Java tutorial. Today, I'm going to be talking about type casting, which is um converting data types essentially. So, like a float to a double, um an int to a string, stuff like that.
It's relatively simple, except converting things to a string. So, I'm going to show everything else first because converting um everything else is a lot simpler.
Let's say I had a float f equals 3.5, and I wanted to make an int i equal f. Well, I can't do that because that's a float. So, I add a cast. See, it already comes up there. So, in print, you put your parentheses, and in there you write what you want to cast it to. So, if I want to make it an integer, it becomes an int and there's no error.
Since you can't actually assign a decimal to i, that will also round it. But I'll give you um, if I had a double d equals double and I put in there f, that converts the f to a double. Just putting the data type in parentheses in front of it will cast it.
So, I could have a char c equals char f. That would convert it to a character, so that's really simple.
But um, converting to strings is different. So, if I had a string s and in int i equals 5, because some methods will only take strings, like especially when you start getting into GUI. If you have some data that are like integers or something you want to display, you need to convert it to a string to um like print it out on the screen or something.
So, string s equals. You have to do new, and that's an integer. You don't type in; you spell out integer in parentheses. What it is do, toString with empty parameters, and you're calling the toString method on this, which is going to convert it i to a string, so it can be assigned to s.
And that's for integer. If I had a double, you have to actually type out the word Integer double with a capital D and the same for float and long and stuff like that.
So that's the toString method, and that's um just basics type casting. So see you in the next tutorial.