Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

tipsmart Q25

 
Cathy Song
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Q25
{
public static void main(String []args)
{
final int i = 100; // line1
byte b = i; // line2
System.out.println(b);
}
}
Why does not line 2 generate a compiler error? If I remove the final keyword from line 1, the result is as I expected.
[ October 20, 2003: Message edited by: Cathy Song ]
 
Thomas De Vos
stable boy
Ranch Hand
Posts: 425
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The final word means that the actually value of "i" is stored in the byte variable "b". The compiler will replace the declaration with byte b = 100;
Without any consequence the compiler can replace the variable with the value.
Even better when you change your code snippet to:
final int i = 128;
byte b = i;
The compiler flags an error. This is because the value 128 (int) cannot be stored in a byte value.
http://www.javacertificate.com
http://www.j2eecertificate.com
[ October 11, 2003: Message edited by: Thomas De Vos ]
 
vinod n.s
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When assigning a final variable to a variable, even if the final variable’s data type is wider than the variable, if the value is within the range of the variable an implicit conversion is done.
byte b;
final int a = 10;
b = a; // Legal, since value of ‘a’ is determinable and within range of b
final int x = a;
b = x; // Legal, since value of ‘x’ is determinable and within range of b
int y;
final int z = y;
b = z; // Illegal, since value of ‘z’ is not determinable

[velmurugans study notes]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does not line 2 generate a compiler error?

Here is the special assignment conversion rule.
variable = expression
The value of an expression can be assigned to a variable if
1. The expression is a constant expression of type byte, short, char, or int
2. The type of the variable is byte, short, or char
3. The value of the expression (which is known at compile-time, because it is a constant expression) can be represented in the type of the variable
----
Constant expressions are described in JLS 15.28.
Literals of primitive type are constant expressions.
Simple names that refer to final variables, whose initializers are constant expressions, are constant expressions.
----
Note: This rule applies not only to variable declarations, but also to return values of methods. This rule does Not apply to arguments of methods.
[ October 11, 2003: Message edited by: Marlene Miller ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic