Thursday, February 10, 2011

Declaring Constants

To declare constants in Java the final keyword is used. Final variables can be set either at compile time or run time. In Java, when the final is used on a primitive it makes the value of the primitive immutable while when used on object references it makes the reference constant meaning that the reference can only point to only one object during its lifetime. Final members can be left uninitialized when declared but then must be defined in the constructor.
To declare constants in C# the const keyword is used for compile time constants while the readonly keyword is used for runtime constants. The semantics of constant primitives and object references in C# is the same as in Java.
Unlike C++, it is not possible to specify an immutable class via language constructs in either C# or Java. Neither is it possible to create a reference through which it's impossible to modify a mutable object.
C# Code

using System;

public class ConstantTest{

/* Compile time constants */
const int i1 = 10; //implicitly a static variable

// code below won't compile because of 'static' keyword
// public static const int i2 = 20;

/* run time constants */
public static readonly uint l1 = (uint) DateTime.Now.Ticks;

/* object reference as constant */
readonly Object o = new Object();

/* uninitialized readonly variable */
readonly float f;


ConstantTest() {
// unitialized readonly variable must be initialized in constructor
f = 17.21f;
}

}

Java Code

import java.util.*;

public class ConstantTest{

/* Compile time constants */
final int i1 = 10; //instance variable
static final int i2 = 20; //class variable

/* run time constants */
public static final long l1 = new Date().getTime();

/* object reference as constant */
final Vector v = new Vector();

/* uninitialized final */
final float f;


ConstantTest() {
// unitialized final variable must be initialized in constructor
f = 17.21f;
}

}
NOTE: The Java language also supports having final parameters to a method. This functionality is non-existent in C#.


The primary use of final parameters is to allow arguments to a method to be accessible from within inner classes declared in the method body.

No comments:

Post a Comment