From my knowledge Implicit casting happens when converting from a smaller data type to a large one for example
double example = 2
which converts an int to a double
Explicit casting however has to be done manually because of data loss right :D
for example int exampleExplicit = 2.2;
The question I wanted to ask all of you is that in the Math class, round method
int Question = Math.round (1.1f);
returns an integer of 1, does that mean that this method automatically explicity casts this float number to an integer?
I'm sorry if this is a stupid question but I just needed clarification :D
CodePudding user response:
Math.round(float)
is just a method. What it does is a black box, but you do know that it requires exactly one parameter, which must be of type float
, it does... something... and then it returns some sort of int
. The java language specification does not know about its existence, and therefore confers nothing special about how it works or what it does.
Therefore, trivially, given that 'casting' is fundamentally a thing that the language spec covers, Math.round(float)
cannot be said to 'implicitly cast'. It's not about whether it does or doesn't - it's about the notion that the question is nonsense in the first place, therefore no answer is available.
Of course, it's not really a mystery meat sandwich: There is javadoc that explains what it does, and you can trust that the javadoc isn't lying to you. It will return the int
with the property that the difference between the float value and that integer is the smallest (no other int it could return would claim to have a smaller difference). How does it accomplish this feat?
Who knows. Who cares. It does what it does, and given that its core library, you can assume it does that reasonably efficiently. If you are just intrigued and wanna know how it works - java is open source, so you can look at the source of Math.round(float)
right here.
You sound like a beginner, which means it's likely that source makes absolutely not one iota of sense to you.
That's sort of my point: Whilst anything is potentially interesting, if your aim is to become a better java programmer, there is an order to things. If someone has never driven a car and has barely seen any in their life, and they want to learn how, you do not start with a 2 week course on the finer details of carburetor design. You don't need to know this in order to drive a car, and without some more understanding of cars and driving in general, you'll constantly be wondering what it's all even for - you're lacking crucial context.
Same here.
Math.round(float)
does what it does. Don't worry about how, not at this phase of your java career.
CodePudding user response:
Short answer: No
Explanation:
The documentation of Math.round() says it Returns the closest int to the argument
So Math.round(1.2f)
will return 1
but Math.round(1.6f)
will return 2
.
However, both int i = (int)1.1;
and int i = (int)1.6;
will assign 1
to i.