Automatic type conversion?

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.

1 Like
  • Java simply upgrades a passed argument to a float if it isn’t already.
  • What Java won’t do is downgrade a double to a float though!
  • So something like this won’t compile: ellipse(56d, 46, 55, 55);.
  • Notice the literal 56 got a d suffix on it, meaning it is of datatype double.
  • 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();
3 Likes

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! :confused:

image

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! :neutral_face:

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”. :wink:

I just can’t stand that feature nagging me all the time while I type in! :face_vomiting:

just tried to disable it, and it still shows the message and refuses to load the sketch.

1 Like
  • 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.
2 Likes

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

2 Likes