The parameters for ellipse() are all of type float (https://processing.org/reference/ellipse_.html). Why does this work when I pass in all ints? Is there type conversion happening in the background? I have been using these 2D shapes for years but never realized that the parameter types are floats.
- Java simply upgrades a passed argument to a
float
if it isn’t already. - What Java won’t do is downgrade a
double
to afloat
though! - So something like this won’t compile:
ellipse(56d, 46, 55, 55);
. - Notice the literal
56
got ad
suffix on it, meaning it is of datatypedouble
. - The only exception I can remember now where Java can downgrade a primitive datatype is when we use 1 of its composite assignment operators such as
+=
,/=
,^=
, etc.:
+= (add assign) / Reference / Processing.org
int a = 10;
a *= PI;
println(a); // 31 instead of 31.415928
exit();
I’ve seen this fail in constructors sometimes though. If you declare float in a constructor and pass an int it will often prompt you to pass a float.
Prompt? Who exactly does it? Never seen it and it has never failed on me!
this is in a method, but it does it with my slider and menu constructors too.
That’s some kinda strange warning, not an error!
Anyways, I didn’t even know about it b/c 1 of the 1st things I do when I install Processing is turn off “Continuously check for errors” option within the PDE’s “Preferences”.
I just can’t stand that feature nagging me all the time while I type in!
- Paying more attention now I’ve found out what’s wrong there.
- It’s requesting a Float instead of a
float
! - Java will fail to auto-coerce a non-corresponding primitive value on such situation.
awesome I failed to realise something so simple. Btw why do the two types exist, I understand that when declaring floats in a array or arrayList it has to be done, but when you are new it hard to find explanations behind the reason for this.
For the ArrayList indeed. But vanilla arrays are more than OK w/ all 8 Java primitive datatypes.
B/c Java generics, the 1s inside the “diamond” <>
, can’t have any of the 8 primitive datatypes!
So we use the corresponding wrapper classes instead:
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Number.html
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Float.html