Thursday, February 10, 2011

Array Declarations

Java has two ways in which one can declare an array, one which is backwards compatible with the notation used in C & C++ and another which is generally accepted as being clearer to read, C# uses only the latter array declaration syntax.
C# Code

int[] iArray = new int[100]; //valid, iArray is an object of type int[]
float fArray[] = new float[100]; //ERROR: Won't compile

Java Code

int[] iArray = new int[100]; //valid, iArray is an object of type int[]
float fArray[] = new float[100]; //valid, but isn't clear that fArray is an object of type float[]

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.

Primitive Types

For every Java primitive type there is a corresponding C# type which has the same name (except for byte). The byte type in Java is signed and is thus analagous to the sbyte type in C# and not the byte type.C# also has unsigned versions of some primitives such as ulong, uint, ushort and byte . The only significantly different primitive in C# is the decimal type, a type which stores decimal numbers without rounding errors (at the cost of more space and less speed).

Below are different ways to declare real valued numbers in C#.
C# Code

decimal dec = 100.44m; //m is the suffix used to specify decimal numbers
double dbl = 1.44e2d; //e is used to specify exponential notation while d is the suffix used for doubles

Reflection

The ability to discover the methods and fields in a class as well as invoke methods in a class at runtime, typically called reflection, is a feature of both Java and C#. The primary difference between reflection in Java versus reflection in C# is that reflection in C# is done at the assembly level while reflection in Java is done at the class level. Since assemblies are typically stored in DLLs, one needs the DLL containing the targeted class to be available in C# while in Java one needs to be able to load the class file for the targeted class. The examples below which enumerate the methods in a specified class should show the difference between reflection in C# and Java.
C# Code

using System;
using System.Xml;
using System.Reflection;
using System.IO;

class ReflectionSample {


public static void Main( string[] args){


Assembly assembly=null;
Type type=null;
XmlDocument doc=null;

try{
// Load the requested assembly and get the requested type
assembly = Assembly.LoadFrom("C:\\WINNT\\Microsoft.NET\\Framework\\v1.0.2914\\System.XML.dll");
type = assembly.GetType("System.Xml.XmlDocument", true);

//Unfortunately one cannot dynamically instantiate types via the Type object in C#.
doc = Activator.CreateInstance("System.Xml","System.Xml.XmlDocument").Unwrap() as XmlDocument;

if(doc != null)
Console.WriteLine(doc.GetType() + " was created at runtime");
else
Console.WriteLine("Could not dynamically create object at runtime");

}catch(FileNotFoundException){
Console.WriteLine("Could not load Assembly: system.xml.dll");
return;
}catch(TypeLoadException){
Console.WriteLine("Could not load Type: System.Xml.XmlDocument from assembly: system.xml.dll");

return;
}catch(MissingMethodException){
Console.WriteLine("Cannot find default constructor of " + type);
}catch(MemberAccessException){
Console.WriteLine("Could not create new XmlDocument instance");
}

// Get the methods from the type
MethodInfo[] methods = type.GetMethods();

//print the method signatures and parameters
for(int i=0; i < methods.Length; i++){

Console.WriteLine ("{0}", methods[i]);

ParameterInfo[] parameters = methods[i].GetParameters();

for(int j=0; j < parameters.Length; j++){
Console.WriteLine (" Parameter: {0} {1}", parameters[j].ParameterType, parameters[j].Name);
}

}//for (int i...)

}

}
Java Code

import java.lang.reflect.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

class ReflectionTest {

public static void main(String[] args) {

Class c=null;
Document d;

try{

c = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().getClass();
d = (Document) c.newInstance();

System.out.println(d + " was created at runtime from its Class object");

}catch(ParserConfigurationException pce){
System.out.println("No document builder exists that can satisfy the requested configuration");
}catch(InstantiationException ie){
System.out.println("Could not create new Document instance");
}catch(IllegalAccessException iae){
System.out.println("Cannot access default constructor of " + c);
}

// Get the methods from the class
Method[] methods = c.getMethods();

//print the method signatures and parameters
for (int i = 0; i < methods.length; i++) {

System.out.println( methods[i]);

Class[] parameters = methods[i].getParameterTypes();

for (int j = 0; j < parameters.length; j++) {
System.out.println("Parameters: " + parameters[j].getName());
}

}
}
}
One might notice from the above code samples that there is slightly more granularity in the C# Reflection API than the Java Reflection API as can be seen by the fact that C# has a ParameterInfo class which contains metadata about the parameters of a Method while Java uses Class objects for that which lose some information such as the name of the parameter.
Sometimes there is a need to obtain the metadata of a specific class encapsulated as an object. This object is the java.lang.Class object in Java and the System.Type object in C#. To retrieve this metadata class from an instance of the target class, the getClass() method is used in Java while the GetType() method is used in C#. If the name of the class is known at compile time then one can avoid creating an instance of the class just to obtain the metadata class by doing the following
C# Code

Type t = typeof(ArrayList);

Java Code

Class c = java.util.Arraylist.class; /* Must append ".class" to fullname of class */

Access Modifiers

Below is a table mapping C# access modifiers to Java's. C++ fans who were disappointed when Sun changed the semantics of the protected keyword in Java 2 will be happy to note that the C# protected keyword has the same semantics as the C++ version. This means that a protected member can only be accessed by member methods in that class or member methods in derived classes but is inaccessible to any other classes. The internal modifier means that the member can be accessed from other classes in the same assembly as the class. The internal protected modifier means that a member can be accessed from classes that are in the same assembly or from derived classes.
C# access modifier Java access modifier
private private
public public
internal protected
protected N/A
internal protected N/A
NOTE: The default accessibility of a C# field or method when no access modifier is specified is private while in Java it is protected (except that derived classes from outside the package cannot inherit the field).

Constructors, Destructors and Finalizers

The syntax and semantics for constructors in C# is identical to that in Java. C# also has the concept of destructors which use syntax similar to C++ destructor syntax but have the mostly the same semantics as Java finalizers. Although finalizers exist doing work within them is not encouraged for a number of reasons including the fact that there is no way to control the order of finalization which can lead to interesting problems if objects that hold references to each other are finalized out of order. Finalization also causes more overhead because objects with finalizers aren't removed after the garbage collection thread runs but instead are eliminated after the finalization thread runs which means they have to be maintained in the system longer than objects without finalizers. Below are equivalent examples in C# and Java.
NOTE: In C#, destructors(finalizers) automatically call the base class finalizer after executing which is not the case in Java.
C# Code
using System;

public class MyClass {

static int num_created = 0;
int i = 0;

MyClass(){
i = ++num_created;
Console.WriteLine("Created object #" + i);
}

~MyClass(){
Console.WriteLine("Object #" + i + " is being finalized");
}

public static void Main(string[] args){

for(int i=0; i < 10000; i++)
new MyClass();

}

}

Java Code
public class MyClass {

static int num_created = 0;
int i = 0;

MyClass(){
i = ++num_created;
System.out.println("Created object #" + i);
}

public void finalize(){
System.out.println("Object #" + i + " is being finalized");
}

public static void main(String[] args){

for(int i=0; i < 10000; i++)
new MyClass();

}

}

Synchronizing Methods and Code Blocks

In Java it is possible to specify synchronized blocks of code that ensure that only one thread can access a particular object at a time and then create a critical section of code. C# provides the lock statement which is semantically identical to the synchronized statement in Java.
C# Code

public void WithdrawAmount(int num){

lock(this){

if(num < this.amount)
this.amount -= num;

}

}

Java Code

public void withdrawAmount(int num){

synchronized(this){

if(num < this.amount)
this.amount -= num;

}

}
Both C# and Java support the concept of synchronized methods. Whenever a synchronized method is called, the thread that called the method locks the object that contains the method. Thus other threads cannot call a synchronized method on the same object until the object is unlocked by the first thread when it finishes executing the synchronized method. Synchronized methods are marked in Java by using the synchronized keyword while in C# it is done by annotating the method with the [MethodImpl(MethodImplOptions.Synchronized)] attribute. Examples of synchronized methods are shown below

C# Code
using System;
using System.Runtime.CompilerServices;

public class BankAccount{

[MethodImpl(MethodImplOptions.Synchronized)]
public void WithdrawAmount(int num){

if(num < this.amount)
this.amount - num;

}

}//BankAccount

Java Code

public class BankAccount{

public synchronized void withdrawAmount(int num){

if(num < this.amount)
this.amount - num;

}

}//BankAccount