C# FAQ: What are the differences between CSharp and Java constant declarations

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

What are the differences between C# and Java constant declarations?

Java constants are declared using the final keyword. Final variables can be set at either compile time or runtime. When the final keyword is used on a primitive, the value of the primitive is immutable. the final keyword is used on an object reference, the immutable reference means that the reference can point only to a single object over its lifetime. Final members can be defined either in the declaration or in the constructor.

import java.util.*;   // Java example
 
public class JavaConstantExamples
{
   // Compile time constants - set at compile time
   static final int integerA = 1;   // class variable 
          final int integerB = 2;   // instance variable 
 
   // runtime constant - set at runtime
   public static final long longTime = 
      new Date().getTime();
  
   // constant object reference 
   final ArrayList arrayList = new ArrayList();
 
   // uninitialized final - set in constructor
   final float floatA; 
  
   JavaConstantExamples()
   {
      floatA = 3.1416f; 
   }
}

C# constants are declared using the const keyword for compile time constants or the readonly keyword for runtime constants. The semantics of constants is the same in both the C# and Java languages.

using System;   // C# example
 
public class CSharpConstantExamples
{
   // Compile time constants - set at compile time
   const int integerA = 1;   // implicitly static
    
   // Following line will not compile due to "static" keyword
   // public static const int integerB = 2; 
 
   // runtime constant - set at runtime
   public static readonly uint longTime =  
      (uint) DateTime.Now.Ticks;
  
   // constant object reference 
   final ArrayList arrayList = new ArrayList();
 
   // uninitialized readonly variable - set in constructor
   readonly float floatA; 
 
   CSharpConstantExamples()
   {
      floatA = 3.1416f; 
   }
}

Whereas the Java language supports final method parameters, C# does not. The primary use of final parameters is to make method arguments accessible from inner classes declared in the method body.

Unlike C++, an immutable class cannot be specified using either C# or Java language constructs. Further, it is not possible to create a reference which cannot be used to modify a mutable object.

See also


Personal tools