Commit e9036454 authored by Dr. Martin Goik's avatar Dr. Martin Goik

Better boxing failure explanation

parent 9294cbc2
......@@ -246,16 +246,23 @@ while (!values.empty()) {
<qandadiv>
<qandaentry>
<question>
<para>Consider the following boxing conversion:</para>
<para>Consider the following two code snippets:</para>
<programlisting language="java">double d = 3.0;
Double dInstance = d;</programlisting>
<informaltable border="0">
<tr>
<td valign="top"><programlisting language="java">Double d = 3.0;</programlisting></td>
<para>This code compiles and executes perfectly well. On contrary
the following snippet does not:</para>
<td valign="top"><programlisting language="java">Double d = 3;</programlisting></td>
</tr>
<programlisting language="java">int i = 3;
Double dInstance = i;</programlisting>
<tr>
<td valign="top">o.K.</td>
<td valign="top"><para>Compile time error:</para><screen>Incompatible types.
Required: java.lang.Double
Found: int</screen></td>
</tr>
</informaltable>
<para>Explain this result. Hint: You may want to read <link
xlink:href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-5.html">chapter
......@@ -267,9 +274,35 @@ Double dInstance = i;</programlisting>
</question>
<answer>
<para>The compiler will not perform auto boxing from
<code>int</code> do <code>Double</code>. On the other hand Double
is no subtype of Integer disallowing a widening reference
<para><quote>3.0</quote> is a double literal. For the sake of
clarification we may rewrite the working code snippet:</para>
<programlisting language="java">double doubleValue = 3.0;
Double d = doubleValue;</programlisting>
<para>With autoboxing on offer the compiler will silently box the
value of type <code language="java">double</code> into a
corresponding instance of type
<classname>Double</classname>.</para>
<para>On contrary <quote>3</quote> is an <code
language="java">int</code> literal allowing for re-writing the
second snippet as:</para>
<programlisting language="java">int intValue = 3.0;
Double d = intValue;</programlisting>
<para>The <quote
xlink:href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-5.html#jls-5.1.7">Boxing
Conversion</quote> section does not define an <code
language="java">int</code> to <classname>Double</classname> boxing
conversion: The compiler will thus not perform auto boxing from
<code>int</code> do <classname>Double</classname>.</para>
<para>An <code language="java">int</code> could however be
auto-boxed into an <classname>Integer</classname>. But
<classname>Double</classname> not being a subtype of
<classname>Integer</classname> disallows a widening reference
conversion.</para>
</answer>
</qandaentry>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment