aspose file tools*
The moose likes Mock Exam Errata and the fly likes final modifier and primitive conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "final modifier and primitive conversion" Watch "final modifier and primitive conversion" New topic
Author

final modifier and primitive conversion

Karlon Wu
Greenhorn

Joined: Jul 09, 2001
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

Joined: May 11, 2001
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).]


Asma Zafar,<BR>Sun Certified Programmer for Java2 Platform
Dave Vick
Ranch Hand

Joined: May 10, 2001
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).]


Dave
Karlon Wu
Greenhorn

Joined: Jul 09, 2001
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

Joined: May 11, 2001
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).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: final modifier and primitive conversion