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

Basic difference

 
Esther Kak
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know this may be basic to many but could somebody explain the difference between compile-time constants and run-time constants.
I am guessing final and static variables are comile time variables. Am I right?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is 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).
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might make sense for a compile-time constant to be static, but that's not a requirement (except in an interface).

"Constant variable" is defined under JLS - 4.12.4 final Variables: "...a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (�15.28) a constant variable." The key here is the definition of "compile-time constant expression," which is the section Keith quoted above.

I don't think the term "runtime constant" is formally defined. But I suppose conceptually...

final int i = (int)(Math.random() * 10);
[ November 08, 2006: Message edited by: marc weber ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic