A question that I came across:

Q: Can you pass a double to a method when it's argument is a float?
A: No. Regardless of the double value, a double-sized variable is too big to fit in a float, so it can't be implicitly cast.

Doubt: Shouldn't narrowing happen implicitly?

Recommended Answers

Shouldn't narrowing happen implicitly?

There could be data lost. The programmer should tell the compiler that he knows what he is doing.

Jump to Post

All 2 Replies

Shouldn't narrowing happen implicitly?

There could be data lost. The programmer should tell the compiler that he knows what he is doing.

commented: Thanks NormR1 :) +0

Java Language Spec says:

5.3 Method Invocation Conversion
Method invocation conversion is applied to each argument value in a method
or constructor invocation (§8.8.7.1, §15.9, §15.12): the type of the argument
expression must be converted to the type of the corresponding parameter.
Method invocation contexts allow the use of one of the following:
• 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
...
If the type of the expression cannot be converted to the type of the parameter by
a conversion permitted in a method invocation context, then a compile-time error
occurs.

so a narrowing conversion like double to float is not allowed.

commented: That was very helpful a read thanks James :) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.