Java: passing an argument with another type of function

In Java, suppose we have a function with the parameter double a . Does it work if I pass an integer as an argument? (I mean, is there an implicit conversion?) And otherwise: if I have, for example, an integer as a parameter, and I pass a double?

Unfortunately, I cannot compile my code at the moment, and I would like to verify this statement. Thank you for attention.

+4
source share
3 answers

For more information on Method Invocation Conversion see JLS - Section No. 5.3 .

Method invocation contexts allow you to use one of the following values:

 - an identity conversion (ยง5.1.1) - a widening primitive conversion (ยง5.1.2) - a widening reference conversion (ยง5.1.5) - a boxing conversion (ยง5.1.7) optionally followed by widening reference conversion - an unboxing conversion (ยง5.1.8) optionally followed by a widening primitive conversion. 

So, your first call ( int to double ) will work fine in accordance with rule No. 2.

But the second call ( double to int ) will give a compiler error, in accordance with the statement below in the same section: -

If the type of the expression cannot be converted to the type parameter by conversion allowed in the context of the method call, a compile-time error occurs.

+10
source

Sometimes you can get around this by making your function with the Number parameter. This is an object that inherits both Integer and Double , so to the point where the Double and Integer numbers behave the same, this will work.

Note that there is a difference between Integer and Double primitives and Integer and Double objects. Java uses autoboxing to automatically convert these types to function calls, etc.

+1
source

Since you can set double to an integer, then an integer as an argument works fine with double as an argument. The other way ends unsuccessfully. In this case, you need to include double in int. The same applies to common goals, for example ..

  int i = 6; double d = 0; d = i; /* ok i = d ; /* not ok 
+1
source

Source: https://habr.com/ru/post/1444658/


All Articles