Wednesday, February 18, 2015

C# vs Java : constants

To declare a constant in Java you use final keyword:
public final String str = "Hello World";
To declare a constant in C# you use the const keyword:
public const string str = "Hello World";

See Also: Java : The final keyword
Constants in C# are static by default.
public class Klass {

   public const string str = "Hello World";

   public static void Main() {
      System.Console.WriteLine("Klass.str = " + Klass.str);
   }
}
Outputs
Klass.str = Hello World
Constants in Java, however, are not.
public class Klass {

   public final String str = "Hello World"; 
   
   public static void main(String... args) {
      System.out.println("Klass.str  = " + Klass.str); // compiler error
      // non-static variable str cannot be referenced from a static context
   }
}
In order for the above program to work the str constant must also be declared as static.
public class Klass {
   public static final String str = "Hello World";

   public static void main(String... args) {
      System.out.println("Klass.str = " + Klass.str);
   }
}
See Also: Java's static Keyword

C# does not allow you declare a constant variable as being static.
public class Klass {
   public static const string str = "Hello World"; // compiler error
   // The constant 'Klass.str' cannot be marked static
}

In C# if you have a const field that's a reference type you can only assign it a null value.
//const MyClass xclass = new MyClass(); // compiler error
   
const MyClass xclass = null;
Strings are the exception to this rule.
const string xstring = "Hello World";
Java does not have this particular restriction.
public class Klass {
   public final Klass klass = new Klass();
}

No comments:

Post a Comment