Skip to content
Snippets Groups Projects
Commit 7bed2714 authored by Goik Martin's avatar Goik Martin
Browse files

byte sum conversion clarification

parent ea1be0ef
No related branches found
No related tags found
No related merge requests found
......@@ -876,14 +876,18 @@ System.out.println("New value=" + a);
<programlisting language="none">value=127
New value=-128</programlisting>
<para>Explain this strange behaviour. Moreover you'll find the
following code snippet yields a compile time error:</para>
<para>Explain this strange behaviour.</para>
<para>Moreover you'll find the following code snippet yields a
compile time error:</para>
<programlisting language="noneJava">byte a = 127;
System.out.println("value=" + a);
a = a + 1; // Error: Type mismatch: cannot convert from int to byte
System.out.println("New value=" + a);</programlisting>
<para>Explain this error's cause.</para>
<tip>
<para>You may want to read the <link
xlink:href="http://proquest.safaribooksonline.com/9780992133047/toc1_html_4">overview
......@@ -925,6 +929,31 @@ System.out.println("New value=" + a);</programlisting>
<para>Conclusion: Watch out when doing (integer)
arithmetic!</para>
<para>The compile time error is due to the definition of the
<quote>+</quote> operator in Java always returning an
<code>int</code> rather than a byte. Consider:</para>
<programlisting language="none"> byte a = 120, b = 10;
System.out.println(a + b);</programlisting>
<para>This yields the expected output of 130 and corresponds to
an <code>int</code> value.</para>
<para>If the expression <code>a + b</code> was of data type
<code>byte</code> an arithmetic overflow as in the subsequent
code example would occur: </para>
<programlisting language="none"> byte a = 120, b = 10;
byte sum = (byte) (a + b);
System.out.println(sum);</programlisting>
<para>The explicit type conversion (a so called type cast or
cast for short) forces the 4-byte integer into a one-byte
variable <code>sum</code> thereby loosing the original value and
returning -126 instead.</para>
</answer>
</qandaentry>
</qandadiv>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment