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 compile time constants and implicit conversions 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 "compile time constants and implicit conversions" Watch "compile time constants and implicit conversions" New topic
Author

compile time constants and implicit conversions

catherine powell
Greenhorn

Joined: Oct 07, 2006
Posts: 26
Hi Everyone,

Given:

1. that the compiler performs an implicit conversion for assignments when an expression is a constant expression of type byte, short, char or int; the type of the variable is type byte, short or char; and the value of the expression is within range.

2. it is legal to access a static variable through a reference to an instance of the class

I don't understand why this doesn't compile:



I'm getting the following compiler error:

CompileTimeConstantTest.java:8: possible loss of precision
found : int
required: byte
byte b = ctc.x + ctc.y;


However, everything compiles and runs as expected if I change the line of code which declares the variable b to read:

byte b = x + y;

Thank you guys very much in advance for your help!

Catherine
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Note that these



do not qualify as compile-time constants.

This is the definition of a compile-time constant from the Java Language Specification 15.28.

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

* Literals of primitive type and literals of type String (�3.10.5)
* Casts to primitive types and casts to type String
* The unary operators +, -, ~, and ! (but not ++ or --)
* The multiplicative operators *, /, and %
* The additive operators + and -
* The shift operators <<, >>, and >>>
* The relational operators <, <=, >, and >= (but not instanceof)
* The equality operators == and !=
* The bitwise and logical operators &, ^, and |
* The conditional-and operator && and the conditional-or operator ||
* The ternary conditional operator ? :
* Parenthesized expressions whose contained expression is a constant expression.
* Simple names that refer to constant variables (�4.12.4).
* Qualified names of the form TypeName . Identifier that refer to constant variables (�4.12.4).
catherine powell
Greenhorn

Joined: Oct 07, 2006
Posts: 26
Thank you very much for the information, Keith.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: compile time constants and implicit conversions
 
Similar Threads
Simple Question on variable assignment
Assignment
implicit casting of final int to byte ???
Automatic typecasting
Final Variable Behavior