Doubt about
Loss of Precision
Please help to explain the following two programs: // This is Compile tile error.
loss of precision ok.
//This
is not error. Why?
This is not an error because the
compiler interprets
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
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[])
This Program is actually executed as : public static void main(String args[])
-- Blessan George
Related:
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.
|