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()) { ...@@ -246,16 +246,23 @@ while (!values.empty()) {
<qandadiv> <qandadiv>
<qandaentry> <qandaentry>
<question> <question>
<para>Consider the following boxing conversion:</para> <para>Consider the following two code snippets:</para>
<programlisting language="java">double d = 3.0; <informaltable border="0">
Double dInstance = d;</programlisting> <tr>
<td valign="top"><programlisting language="java">Double d = 3.0;</programlisting></td>
<para>This code compiles and executes perfectly well. On contrary <td valign="top"><programlisting language="java">Double d = 3;</programlisting></td>
the following snippet does not:</para> </tr>
<programlisting language="java">int i = 3; <tr>
Double dInstance = i;</programlisting> <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>
<para>Explain this result. Hint: You may want to read <link <para>Explain this result. Hint: You may want to read <link
xlink:href="">chapter xlink:href="">chapter
...@@ -267,9 +274,35 @@ Double dInstance = i;</programlisting> ...@@ -267,9 +274,35 @@ Double dInstance = i;</programlisting>
</question> </question>
<answer> <answer>
<para>The compiler will not perform auto boxing from <para><quote>3.0</quote> is a double literal. For the sake of
<code>int</code> do <code>Double</code>. On the other hand Double clarification we may rewrite the working code snippet:</para>
is no subtype of Integer disallowing a widening reference
<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
<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
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> conversion.</para>
</answer> </answer>
</qandaentry> </qandaentry>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment