Doubt about Loss of Precision

Please help to explain the following two programs:

// This is Compile tile error. loss of precision ok.
     class AboutByte1
     {
     public static void main(String args[])
     {
     byte a=5;
     a=a+a;
     System.out.println(a);
     }
     }

     //This is not error. Why?
     class AboutByte2
     {
     public static void main(String args[])
     {
     byte a=5;
     a+=a;
     System.out.println(a);
     }
     }

This is not an error because the compiler interprets
a+=a;
as
a = (byte)a+a

That is because of the implicit conversion. All numbers are implicitly converted to an int. JLS chapter 5 tell about this.

In the JVM every variable is converted to an int before performing any operation on it.

Case 1: You get Compile time error when u perform a=a+a;

Reason : In Java, any time you perform a binary operation Binary Numeric Promotion is performed.Binary Numeric Promotion casts each operand up to the size of the other or, if neither is larger than an int, both are cast as ints.In case of byte  it is stored as 32 bit.So when u perform a+a it return an integer.That's why you're getting a compiler error- the +(addition) operation is returning an int and we know that we can't assign an int to a byte without a cast because that's a narrowing conversion.

Therefore, in order to make the above code work, you must add a cast
        a=(byte) a+a;

Case 2: Not getting error when u perform a+a;

Reason : Implicit Explicit Casts.There is a case in which an explicit cast is implied. The answer is a compound assignment operator. Compound assignment operators, such as +=, -=, *= all contain an explicit cast, even though it's not shown.

Take the ex:

public static void main(String args[])
{
byte a=5;
a+=a;
System.out.println(a);
}

This Program is actually executed as :

public static void main(String args[])
{
byte a=5;
a=(byte)a+a;
System.out.println(a);
}

-- Blessan George

Related:

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.