From 7bed2714bc39810427f6c2f1127b3cb26538bb9c Mon Sep 17 00:00:00 2001
From: Martin Goik <goik@hdm-stuttgart.de>
Date: Sun, 13 Sep 2015 20:00:19 +0200
Subject: [PATCH] byte sum conversion clarification

---
 Doc/Sd1/languageFundamentals.xml | 33 ++++++++++++++++++++++++++++++--
 1 file changed, 31 insertions(+), 2 deletions(-)

diff --git a/Doc/Sd1/languageFundamentals.xml b/Doc/Sd1/languageFundamentals.xml
index d31450d6a..7e9028c6c 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>
-- 
GitLab