Program: final byte a = 10; final byte b = 12; byte c = a * b; I don't understand why will this program correct. According to the text book, the arithmetic promotion will be: For binary operators(i.e. +,-,*,/): 1.If one of the operands is double, then th other is converted to double 2.Else if one of the operands is float, then the other is converted to float 3.Else if one of the operands is long, then the other is converted to long 4.Else both are converted to int. Back to the topic. Though we can't modify a and b to int, the * operator should also give a integer back. Can somebody explain this situation?
Do you know, you have to accept it. Its the way JVM works. e.g
int i =1; byte b; b = i ; //Compiler error. but consider, the following example,\ byte b; final int i = 2; b = i; // works perfectly fine. So for final variables there is a confusion in JVM behaviour. [This message has been edited by Asma Zafar (edited July 10, 2001).] [This message has been edited by Asma Zafar (edited July 10, 2001).]
Asma Zafar,<BR>Sun Certified Programmer for Java2 Platform
Karlon and Asma It isn't a confusion in the JVM is the design of the compiler that allows this. When an operand is final the compiler knows its value can't change so it allows the narrowing conversion with no complaint and without an explicit cast if it will indeed fit within the type it is being assigned to. hope that helps
Dave If this isn't from a mock exam or book then you may want to move it to one of the general forums. [This message has been edited by Dave Vick (edited July 10, 2001).]
Joined: Jul 09, 2001
Thanks, Dave. It's not a mock. I saw this question in one of the posts of this forum, so I asked. Sorry for that, and thanks anyway.
Joined: May 11, 2001
Even if its the how the compiler works, but its not true for all final data types. Its valid for only primitive integral data type, like byte, short, int only (excluding long), float or double. i.e. final int i =1; final short s = 2; final long l= 3; byte b; b=i; // no error b = s ; // no erro // b = l; // Compiler Error
[This message has been edited by Asma Zafar (edited July 14, 2001).]