Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt with the final key

 
Kitty Dayal
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I couldn't make difference between the two snippet's below



The first one compiles out, while other runs fine. The only diff is using the final key in the second. This is from dan's questions and he does not mention anything on the final key.

Thanx.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kitty,

Thank you for using my exam.

The first code fragment is as follows.

char c1 = 1;
byte a = c1;

In the first case, the code attempts to assign a char value to a byte variable. The char is a 16 bit unsigned type while byte is an 8 bit signed type. As you can imagine, there are a lot of char values that can not be represented by a variable of type byte.

The second code fragment is as follows.

final char c1 = 1;
byte a = c1;

In the second case, the "final" modifier is added to the declaration of the char variable. As a result, the char variable is now a compile-time constant. The compiler recognizes that the constant value, 1, can be assigned to a variable of type byte.

This is covered in
Section 5.2 of the Java Language Specification.
 
Kitty Dayal
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dan.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic