File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting" Watch "casting" New topic
Author

casting

sudha siva
Ranch Hand

Joined: Sep 18, 2001
Posts: 30
public class AnotherDirtyOne
{
private final int i =10;
private byte k = i; // line 1
}

public class AnotherDirtyOne{
private int i=10;
privete byte k=i;// line 2
}
The compiler is objected in line 2.(Explicit cast needed to convert int to byte.) But there was no compiler error in line 1.In line 1 also int value is assigned to byte variable.Can anyone tell me why there was no compiler erroe in line 2(Is it because of the final)

Thanks
sudha
Uma Viswanathan
Ranch Hand

Joined: Jun 14, 2001
Posts: 126
Yes...if you assign the value of final variable to a variable of diff type and (even if the value of the final variable is wider than the range of the L.H.S variable type) and if the value is determinable at compile time, then implicit conversion will take place at compile time.
Hope this helps...
Uma
Nain Hwu
Ranch Hand

Joined: Sep 16, 2001
Posts: 139
Sudha,
Line 2 is rejected because it tries to assign a non-compile constant int value to a byte. It needs a explicit cast, while line 1 is accepted because it assigns a compile time
constant value (within the range of byte)
to a byte.
This is straight from JLS �5.2:

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.



[This message has been edited by Nain Hwu (edited November 29, 2001).]
Fei Ng
Ranch Hand

Joined: Aug 26, 2000
Posts: 1242
Like this..
public class AnotherDirtyOne
{
private final int i =10;
private byte k = i; // line 1
// at compile time, the statement actually look like this
private byte k = 10; // so it works
}

public class AnotherDirtyOne{
private int i=10;
privete byte k=i;// line 2
// Here, the i stay unknow which means not in a range of byte. So compile time error
}
[This message has been edited by FEI NG (edited November 29, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting