diff --git a/Doc/Sd1/languageFundamentals.xml b/Doc/Sd1/languageFundamentals.xml index d31450d6a319bc0e0c52e0bfbb3b67fcf3a3dfc0..7e9028c6ceaeaf1cbb367458687f48b91559a6a2 100644 --- a/Doc/Sd1/languageFundamentals.xml +++ b/Doc/Sd1/languageFundamentals.xml @@ -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>