This week's book giveaways are in the Refactoring and Agile forums.We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!

# final modifier and primitive conversion

Karlon Wu
Greenhorn
Posts: 4
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?

Asma Zafar
Ranch Hand
Posts: 49
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).]

Dave Vick
Ranch Hand
Posts: 3244
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).]

Karlon Wu
Greenhorn
Posts: 4
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.

Asma Zafar
Ranch Hand
Posts: 49
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

Asma Zafar

[This message has been edited by Asma Zafar (edited July 14, 2001).]