Java primitives and overloading

I always heard (and thought) Java as a strongly typed language. But only recently I noticed something that I used almost daily: overload intand double.

I can write the following, and this is really Java code:

int i = 1;
double j = 1.5;
double k = i + j;

But if I have a method, one of the arguments of which is double, I need to specify it:

public static <K, V> V getOrDefault(K k, Map<K, V> fromMap, V defaultvalue) {
    V v = fromMap.get(k);
    return (v == null) ? defaultvalue : v;
}

When I call the above method on Map<String, Double>, the argument defaultvaluecannot be int:

getOrDefault(aString, aStringDoubleMap, 0); // won't compile
getOrDefault(aString, aStringDoubleMap, 0d); // compiles and runs just fine

Why does Java overload intin double(as well as in addition to this) and then automatically add it to double? I think the answer is how Java performs operator overloading (i.e., Overloading occurs in the operator +, not from intto double), but I'm not sure.

, SO .

+4
4

, . .

getOrDefault(aString, aStringDoubleMap, 0); // won't compile

, Java 0 Integer, - Double. . ,

Double value = 3; // Type mismatch: cannot convert from int to Double

JLS,

, , .

0, , int. Loose invocation

, , . Loose invocation :

  • (§5.1.1)
  • (§5.1.2)
  • (§5.1.5)
  • (§5.1.7),
  • (§5.1.8),

int Double .

public static void main(String[] args) throws Exception {
    method(3);
}

public static void method(double d) {
}

.

+4

5.2 Java Language.

, int double, . , Autobox int Double. .

+3

Java ( - String concat (+)).

double k = i + j;

. . JVM.

getOrDefault, generics.And autoboxing. getOrDefault(aString, aStringDoubleMap, 0d);, 0d Double Object. JVM 0 Double .

Java ( 0 0d) (double to Double) .

Implicit casting from int to double followed by boxing in Double is not allowed.

0 can only be autoboxed for Integer. 0d can be auto-boxed in Double.

+1
source

The transform intdoubleis an expanding transform. Enhanced conversions do not result in data loss, so they are automatically performed .

-1
source

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


All Articles