Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Type casting  RSS feed

 
Arpitha Ramesh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I am new to java,please help me in understanding these concepts,

1. int i=5;
byte b=i; //which throws error

final int i=5;
byte b=i; //works fine

2.final int a[]=new int[10];
final is used for constant,but we can add values to this declaration.

Please explain.

Thanks,
Arpitha


what is the reason for this.please expalin.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Final is used to prevent a variable from being assigned to more than once. In your example the variable is a reference to an array of int. Whether or not the array is mutable is irrelevent, the variable's value cannot change.
 
Nirmal Vidura
Greenhorn
Posts: 9
Hibernate jQuery Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i=5;
byte b=i; //which throws error

It is true that i is within byte range. But it is in an int block which is 32 bits. So you can not assign 32-bit value to 8-bit without casting explicitly.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the Java Language Specification says about assignment conversions.

Assignment conversion occurs when the value of an expression is assigned (�15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (�5.1.1), a widening primitive conversion (�5.1.2), or a widening reference conversion (�5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:

* The expression is a constant expression of type byte, short, char or int.
* The type of the variable is byte, short, or char.
* The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context, then a compile-time error occurs.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, the first example doesn't work because "i" is not a compile-time constant. If i is a compile-time constant then the compiler can safely do the conversion because it knows the value of i can be converted to a byte. When i is not a compile-time constant there's no way for the compiler to know if the conversion can be made.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!