This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compile time constants and implicit conversions

 
catherine powell
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the information, Keith.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic